我有一个实现IHttpHandler和IRouteHandler的类
public class CustomHandler : IHttpHandler,IRouteHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("Content-Type", "text/plain");
context.Response.Write("Hello World");
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return this;
}
}在Application_Start方法中,我尝试用路由注册处理程序:
Route route = new Route("dav/{*Pathinfo}", new CustomHandler());
RouteTable.Routes.Add(route);在我用这种Url调用之前,一切都很酷:
http://localhost:63428/dav/asdadsahttp://localhost:63428/dav/asdadsa/asdasdhttp://localhost:63428/dav/asdadsa/a%20%20sdasd (在url中有空格)
但如果我试着用它们:http://localhost:63428/dav/asdadsa.docxhttp://localhost:63428/dav/asdads/a.docx
我的处理程序没有调用,服务器返回404。我认为通配符将匹配以dav/开头的每个url。
知道如何实现带有扩展的urls也与我的路径匹配吗?更新:
我找到了这个页面。
它是从配置设置的,而不是从后面的代码中设置的,但是不需要设置runAllManagedModulesForAllRequests设置,不幸的是,在我最初的示例中,没有得到如此干净的路由值。
如果到这个问题上来寻求答案,也许会有人心烦意乱。
发布于 2013-08-29 10:40:45
如果将以下配置添加到web.config文件中,则路由也将包括文件。
<configuration>
<system.webServer>
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
<!-- more -->
</modules>
</system.webServer>
</configuration>一种不同的解决方案是添加<modules runAllManagedModulesForAllRequests="true">,但这带来了开销,因为所有注册的HTTP模块都运行在每个请求上,而不仅仅是托管请求(例如.aspx)。这意味着模块将在每个.jpg、.gif、.css、.html、.pdf等上运行。
您可以阅读更多关于不同路由设置的这里。
请记住,如果要将特殊路由添加到现有路由中,则必须先添加路由,否则将不会进行处理,如本例所示。
Route route = new Route("dav/{*Pathinfo}", new CustomHandler());
routes.Add(route);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);这种方法的一个问题是,第一个路由定义混淆了系统中的helpers,因此您将不再获得像localhost/home/index这样的好路由,而是localhost/dav?action=index&controller=home。解决方案是将第一条路由限制为仅在传入路由请求时有效。这可以通过创建RouteConstraint并将其添加到RouteValueDictionary中的路由定义来完成。
public class OnlyIncomingRequestConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest)
return true;
return false;
}
}然后,您可以这样重新定义您的路由定义:
Route route = new Route("dav/{*Pathinfo}", new RouteValueDictionary(new { controller = new OnlyIncomingRequestConstraint() }), new CustomHandler());
routes.Add(route);在此之后,您的默认路由将再次恢复正常。
https://stackoverflow.com/questions/18506729
复制相似问题