【问题标题】:Path with json extension not handled by custom handler自定义处理程序未处理具有 json 扩展名的路径
【发布时间】:2016-03-03 07:52:24
【问题描述】:

我正在尝试添加自定义处理程序 - DayOfWeekHandler(参考Pro ASP.NET MVC 5 Platform Book 进行设置)。

routes.config 中的路由:

routes.Add(new Route("handler/path", new CustomHandler() 
{ HandlerType = typeof(DayOfWeekHandler) }));

自定义处理程序:

public class CustomHandler : IRouteHandler
{
    public Type HandlerType;
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return (IHttpHandler)Activator.CreateInstance(HandlerType);
    }
}

当我在浏览器中输入“http://localhost:81/handler/path”时 - 它正确地从处理程序调用 ProcessRequest 方法,但是当我输入“http://localhost:81/handler/path.json”时,我收到 404.0 错误:

HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. In this case it is not even calling Process Request method.

DayOfWeekHandler 中的ProcessRequest 方法:

public void ProcessRequest(HttpContext context)
{
            string day = DateTime.UtcNow.DayOfWeek.ToString();

            context.Response.Write($"Hello from {GetType().Name} Handler :)");
            if (context.Request.CurrentExecutionFilePathExtension == ".json")
            {
                context.Response.ContentType = "application/json";
                context.Response.Write($" \"day\" : \"{day}\" ");
            }
            else
            {
                context.Response.ContentType = "text/html";
                context.Response.Write($"<div>It is {day}!</div><br/>");
            }
}

此外,当处理程序在 web.config 文件中注册时,它工作正常。 我是不是错过了什么。请帮助我理解为什么 /handler/path.json 没有被渲染。

【问题讨论】:

    标签: c# asp.net-mvc routes httphandler global-asax


    【解决方案1】:

    我必须将 Web.config 添加到包含我的 JSON 的文件夹中

    <?xml version="1.0"?>
    <configuration>
        <system.webServer>
          <staticContent>
            <mimeMap fileExtension=".json" mimeType="application/json" />
          </staticContent>
        </system.webServer>
    </configuration>
    

    我假设您也可以将其添加到您的根配置中

    【讨论】:

    • 出现以下错误:无法添加类型为“mimeMap”且唯一键属性“fileExtension”设置为“.json”的重复集合条目
    • 检查 web.config 中的部分。虽然,我怀疑它是否已经存在,但您的问题与我的不同。
    猜你喜欢
    • 2020-11-08
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2015-07-21
    • 1970-01-01
    相关资源
    最近更新 更多