【问题标题】:Custom HttpHandler not firing, returning 404 in ASP.NET MVC Application自定义 HttpHandler 未触发,在 ASP.NET MVC 应用程序中返回 404
【发布时间】:2009-05-14 13:10:00
【问题描述】:

我不知道在 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 路径的引用。

【问题讨论】:

    标签: c# asp.net-mvc httphandler


    【解决方案1】:

    我怀疑这与您使用 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}");
    }
    

    【讨论】:

    • 太好了,这让我朝着正确的方向前进!我在 RegisterRoutes 方法中添加了这一行,它将阻止 MVC 处理请求: routes.IgnoreRoute("{resource}.imu/{*pathInfo}");
    • 如果您想忽略所有路径中的扩展名,请使用 routes.IgnoreRoute("{allimu}", new {allimu=@".*\.imu(/. )?"});来自菲尔哈克haacked.com/archive/2008/07/14/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多