ASP.NET MVC - Routing - an action with file extension

喜你入骨 提交于 2019-11-27 09:01:20
Ben Foster

You need to map requests for your XML files to TransferRequestHandler in web.config. Otherwise IIS will handle the request.

Jon Galloway explains how to do this here.

In summary, you add this element to location/system.webServer/handlers in your web.config:

<add name="XmlFileHandler" path="*.xml" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

The problem is that IIS will handle the .xml file as a static file and will by default not route the XML file through your MVC application. IIS handles the request and your MVC code never gets a change to route to this file. There are a few ways around this.

I've found the easiest way to handle this by using the IIS Rewrite module to rewrite the URL from static file URL(s) to an MVC route:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Live Writer Manifest">
        <match url="*.xml"/>
        <action type="Rewrite" url="route/xmlfilehandler"/>
      </rule>
    </rules>
  </rewrite>
</system.webServer>

Make sure you have the IIS Rewrite Module installed (separate install from the Platform Installer). If you already are using the Rewrite handler this is the most efficient solution.

As pointed out above by Ben Foster and Jon Galloway's post, you can also map the TransferRequestHandler at your specific path you want to route. For compactness here's what you need to add to your web.config:

<system.webServer>
  <handlers>
     <add name="Windows Live Writer Xml File Handler"
       path="wlwmanfest.xml"
       verb="GET" type="System.Web.Handlers.TransferRequestHandler"
       preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" 
     />
  </handlers>
</system.webServer>

You can then use an Attribute Route to handle .xml file Urls. For example:

[Route("blog/wlwmanifest.xml")]
public ActionResult LiveWriterManifest() {... }

More info in this blog post: http://weblog.west-wind.com/posts/2015/Nov/13/Serving-URLs-with-File-Extensions-in-an-ASPNET-MVC-Application

Ayo Adesina

If you drop your xml file in one of the folders inside your website. Try something like this: C# - How to make a HTTP call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!