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

Pet*_*ter 12 c# asp.net-mvc httphandler

我不知道在MVC网站上发生这种情况是否相关,但我认为无论如何我都会提到它.

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

<add verb="*" path="*.imu" type="Website.Handlers.ImageHandler, Website, Version=1.0.0.0, Culture=neutral" />
Run Code Online (Sandbox Code Playgroud)

在网站项目中,我有一个名为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; }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我运行我的网站并转到/something.imu它只会返回404错误.

我正在使用Visual Studio 2008并尝试在ASP.Net开发服务器上运行它.

我一直在寻找几个小时,并让它在一个单独的空网站上工作.所以我不明白为什么它不能在现有的网站内工作.没有其他引用*.imu路径顺便说一句.

sam*_*son 32

我怀疑这与您使用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()
    ));
}
Run Code Online (Sandbox Code Playgroud)

然后ImageRouteHandler该类将返回您的自定义ImageHttpHandler,虽然通过查看Web上的示例,可能更好地更改它以实现MvcHandler,而不是直接IHttpHandler.

编辑1:根据Peter的评论,您也可以使用以下IgnoreRoute方法忽略扩展:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.imu/{*pathInfo}");
}
Run Code Online (Sandbox Code Playgroud)

  • 太棒了,这让我朝着正确的方向前进!我在RegisterRoutes方法中添加了这一行,它将阻止MVC处理请求:routes.IgnoreRoute("{resource} .imu/{*pathInfo}"); (4认同)