自定义HttpHandler未触发,ASP.NET MVC应用程序返回404错误

13

我不知道这是否和MVC网站相关,但还是想提一下。

在我的web.config中,我有以下几行代码:

<add verb="*" path="*.imu" type="Website.Handlers.ImageHandler, Website, Version=1.0.0.0, Culture=neutral" />
在网站项目中,我有一个名为Handlers的文件夹,其中包含我的ImageHandler类。它长这样(我已经删除了processrequest代码)。
using System;
using System.Globalization;
using System.IO;
using System.Web;

namespace Website.Handlers
{
    public class ImageHandler : IHttpHandler
    {
        public virtual void ProcessRequest(HttpContext context)
        {
            //the code here never gets fired
        }

        public virtual bool IsReusable
        {
            get { return true; }
        }
    }
}
如果我运行我的网站并访问/something.imu,它只会返回404错误。
我正在使用Visual Studio 2008,并尝试在ASP.Net开发服务器上运行它。
我已经寻找了几个小时并在一个单独的空网站中使其工作。因此,我不明白为什么它不能在现有网站内工作。顺便说一下,没有其他对*.imu路径的引用。
1个回答

35

我怀疑这与您使用MVC有很大关系,因为它基本上掌控了所有传入的请求。

我认为您需要使用路由表,并可能创建一个新的路由处理程序。我自己没有做过这个,但类似于这样的东西可能有效:

void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.Add(new Route
    (
         "{action}.imu"
         , new ImageRouteHandler()
    ));
}

然后ImageRouteHandler类将返回您的自定义ImageHttpHandler,尽管从网上的示例中看,最好将其更改为实现MvcHandler,而不是直接使用IHttpHandler

编辑1:根据Peter的评论,您还可以通过使用IgnoreRoute方法来忽略扩展名:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.imu/{*pathInfo}");
}

4
太好了,这让我朝着正确的方向前进!我已经在RegisterRoutes方法中添加了这行代码,它将阻止MVC处理该请求:routes.IgnoreRoute("{resource}.imu/{*pathInfo}"); - Peter
1
如果您想在所有路径中忽略扩展名,请使用routes.IgnoreRoute("{*allimu}", new {allimu=@"..imu(/.)?"});,来自Phill Haack的文章http://haacked.com/archive/2008/07/14/make-routing-ignore-requests-for-a-file-extension.aspx/。 - jsturtevant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接