你的代码是正确的,应该Application_Start
放在Global.asax
. 例如:
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new Route(
"sitemap.xml", new PageRouteHandler("~/sitemap.aspx")));
}
但是,您还需要确保 *.xml 文件由 ASP.NET 处理。默认情况下,*.xml 文件将仅由 IIS 提供,而不由 ASP.NET 处理。要确保它们由 ASP.NET 处理,您可以:
1)在您runAllManagedModulesForAllRequests="true"
的system.webServer
元素上指定web.config
:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
</modules>
</system.webServer>
或 2) 为 .xml 文件添加“处理程序映射”:
<system.webServer>
<handlers>
<add name="xml-file-handler" path="*.xml" type="System.Web.UI.PageHandlerFactory"
verb="*" />
</handlers>
</system.webServer>
我在一个示例 ASP.NET(非 MVC)项目中对此进行了测试,并且能够使路由按您指定的方式工作。