我有一個項目需要對MVC的圖像http請求的默認路由行爲進行更改。IHttpHandler GetHttpHandler不會觸發的情況
例如,該樣品從RouteConfig.cs
Route ImagesRoute = new Route("{controller}/{folderName}/{fileName}", new ImageRouteHandler());
string regexWindowsFilePattern = @"^([^\x00-\x1f\\?/%*:|" + "\"" + @"<>]+)\.(?:jpeg|jpg|tiff|gif|png)";
ImagesRoute.Constraints = new RouteValueDictionary { { "fileName", regexWindowsFilePattern } };
routes.Add(ImagesRoute);
應該重新路由
http://localhost/home/contents/image.jpg
到磁盤上的路徑(C:\緩存\ [FOLDERNAME] [文件名])。在我的情況下,「重新路由」只是根據請求寫入正確的http響應。在一個項目中(讓我們稱之爲「測試」項目),這段代碼觸發了正常的行爲:ImageRouteHandler類的GetHttpHandler方法被擊中並且圖像出現在瀏覽器中,但是在其他項目中,RouteConfig.cs和ImageRouteHandler的代碼完全相同,只需插入GetHttpHandler不會觸發這將導致404 NOT FOUND http錯誤。這個其他項目(「目標」項目)具有幾乎相同的配置(我檢查了相關的差異),並且已經在同一個IIS Express服務器上運行。創建新項目並填入目標內容和測試項目會導致正常行爲(即圖像顯示在瀏覽器中)。 任何線索可能是什麼解決方案?
update_1:
我忘了提及這個動作不是故意使用的。我有一個html文件,我必須將其包含到將呈現html文件正文的部分視圖中。我無法控制如何創建此文件,但我有一個定義的結構:名稱爲[htmlFileName]的html文件和名稱爲[htmlFileName] .files的資源文件夾名稱。當我請求一個特定的URL(比如localhost/[Controller]/[Action])時,HTML標記中對資源的引用會導致不正確的URL(http:// localhost/[Controller]/[folderName]/[fileName]),需要重寫這些URL,以便瀏覽器的http映像請求得到很好的回答。那就是爲什麼我認爲這個自定義處理程序是需要的
using System;
using System.Net;
using System.Web;
using System.IO;
using System.Web.Routing;
namespace MyProject.WebUI.Interface.Utility
{
public class ImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string fileName = requestContext.RouteData.Values["fileName"] as string;
string folderName = requestContext.RouteData.Values["folderName"] as string;
if (string.IsNullOrEmpty(fileName))
{
// return a 404 NOT FOUND HttpHandler here
requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
}
else
{
requestContext.HttpContext.Response.Clear();
if (requestContext.HttpContext.Request.Url != null)
{
requestContext.HttpContext.Response.ContentType =
GetContentType(requestContext.HttpContext.Request.Url.ToString());
}
else
{
requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
requestContext.HttpContext.Response.End();
}
// find physical path to image here.
string filepath = @"c:\Cache" + @"\" + folderName + @"\" + fileName;
/*If file exists send the response, otherwise set HTTP 404 NOT FOUND status code for response.*/
if (File.Exists(filepath))
{
requestContext.HttpContext.Response.WriteFile(filepath);
requestContext.HttpContext.Response.End();
}
else
{
requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
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 ".jpeg": return "Image/jpg";
case ".png": return "Image/png";
default: break;
}
return "";
}
}
}
我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –