asp.net-mvc - ASP.NET MVC 2.0 + IRouteHandler 的实现不会触发

标签 asp.net-mvc iroutehandler

谁能帮我解决这个问题,我不知道为什么 公共(public) IHttpHandler GetHttpHandler(RequestContext requestContext) 没有执行。在我的 Global.asax.cs 中我有

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

        routes.Add("ImageRoutes", new Route("Images/{filename}", new CustomRouteHandler()));

    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

//CustomRouteHandler 实现如下

public class CustomRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        // IF I SET A BREAK POINT HERE IT DOES NOT HIT FOR SOME REASON.  
        string filename = requestContext.RouteData.Values["filename"] as string;

        if (string.IsNullOrEmpty(filename))
        {
            // return a 404 HttpHandler here 
        }
        else
        {
            requestContext.HttpContext.Response.Clear();
            requestContext.HttpContext.Response.ContentType = GetContentType(requestContext.HttpContext.Request.Url.ToString());

            // find physical path to image here.   
            string filepath = requestContext.HttpContext.Server.MapPath("~/logo.jpg");

            requestContext.HttpContext.Response.WriteFile(filepath);
            requestContext.HttpContext.Response.End();

        }
        return null;
    }
}

任何人都可以告诉我我在这里缺少什么。简单地 public IHttpHandler GetHttpHandler(RequestContext requestContext) 不触发。

我也没有更改 web.config 中的任何内容。我在这里缺少什么?请帮忙。

最佳答案

routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

routes.Add("ImageRoutes", new Route("Images/{filename}", new CustomRouteHandler()));

你需要翻转这两个声明。 {controller}/{action}/{id} 可能与传入的 URL 匹配,因此您需要在它之前声明您的特殊 Images/{filename}

关于asp.net-mvc - ASP.NET MVC 2.0 + IRouteHandler 的实现不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2441268/

相关文章:

c# - 用户在View中修改model的隐藏值(@Html.HiddenFor)

asp.net-mvc - aspnet-api-versioning 有什么好处?

asp.net-mvc - 带有 tab-id 的 RedirectToAction()

asp.net-mvc - 发布应用程序时的 .Net Core React SPA 路由问题

asp.net-mvc - asp.net mvc 4 - 谁调用_ViewStart.cshtml,步骤顺序是什么

c# - Web 窗体中的 IRouteHandler : Routing requests that require HttpContext. 用户

asp.net - 如何让 ASP.NET MVC 从 IRouteHandler.GetHttpHandler() 识别 IHttpAsyncHandler?

c# - 如何将用户从 MVC 自定义路由器处理程序重定向到另一个 Url?