【发布时间】:2011-12-10 00:31:59
【问题描述】:
我使用带有路由的 Asp.Net 4 C#。
我使用路由将 URL 重新路由到实际的物理文件。我的代码与this one 完全相同。
我的目标是使用自定义路由创建图像src 属性,但将图像的物理路径放在不同的文件夹中。
示例输出路线:
<img alt="" src="/cdn/img/cms/e71e75ef-4906-4d04-8da5-bd459c7b9205/titolo-image.jpg"/>
物理路径:
/cdn/img/cms/images/large/e71e75ef-4906-4d04-8da5-bd459c7b9205.jpg
在使用 Visual Studio 2010 在本地环境中进行测试时,CASSINI 一切正常,但只要网站在使用 IIS 7.5 的生产环境中运行,图像src 就会找不到结果。
我认为 IIS 没有以与 .Net 页面相同的方式处理对静态文件 .jpg 的请求。
我想知道解决这种情况的方法。
这是我用来扩展图像路由的代码..
使用系统; 使用 System.Collections.Generic; 使用 System.IO; 使用 System.Linq; 使用 System.Web; 使用 System.Web.Routing;
namespace WebProject.Cms.BusinessLogics.SEO.Routing
{
/// <summary>
/// Handler Custom Class for Asp.Net Routing. Routing URL's (Virtual paths) to actual physical files.
/// <remarks>Resource at: http://www.phpvs.net/2009/08/06/aspnet-mvc-how-to-route-to-images-or-other-file-types/</remarks>
/// </summary>
public class ImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string filename = requestContext.RouteData.Values["RowGuid"] as string;
string size = requestContext.RouteData.Values["Size"] as string;
string imageType = requestContext.RouteData.Values["ImageType"] as string;
bool hasFileName = !string.IsNullOrEmpty(filename);
bool hasSize =
size == "large" ||
size == "medium" ||
size == "small";
bool hasImageType =
imageType == "jpg" ||
imageType == "bmp" ||
imageType == "gif" ||
imageType == "png";
if (!hasFileName || !hasSize || !hasImageType)
{
requestContext.HttpContext.Response.Clear();
requestContext.HttpContext.Response.StatusCode = 404;
requestContext.HttpContext.Response.End();
}
else
{
requestContext.HttpContext.Response.Clear();
requestContext.HttpContext.Response.ContentType = GetContentType(requestContext.HttpContext.Request.Url.ToString());
// Find physical path to image.
string filepath = requestContext.HttpContext.Server.MapPath("~/Cdn/Cms/Images/" + size + "/" + filename + "." + imageType);
requestContext.HttpContext.Response.WriteFile(filepath);
requestContext.HttpContext.Response.End();
}
return null;
}
private static string GetContentType(String path)
{
switch (Path.GetExtension(path))
{
case ".bmp": return "Image/bmp";
case ".gif": return "Image/gif";
case ".jpg": return "Image/jpeg";
case ".png": return "Image/png";
default: break;
}
return "";
}
}
}
【问题讨论】:
标签: c# asp.net asp.net-mvc iis-7 routing