How to add route to dynamic robots.txt in ASP.NET MVC?

最后都变了- 提交于 2019-12-30 08:52:52

问题


I have a robots.txt that is not static but generated dynamically. My problem is creating a route from root/robots.txt to my controller action.

This works:

routes.MapRoute(
name: "Robots",
url: "robots",
defaults: new { controller = "Home", action = "Robots" });

This doesn't work:

routes.MapRoute(
name: "Robots",
 url: "robots.txt", /* this is the only thing I've changed */
defaults: new { controller = "Home", action = "Robots" });

The ".txt" causes ASP to barf apparently


回答1:


You need to add the following to your web.config file to allow the route with a file extension to execute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- ...Omitted -->
  <system.webServer>
    <!-- ...Omitted -->
    <handlers>
      <!-- ...Omitted -->
      <add name="RobotsText" 
           path="robots.txt" 
           verb="GET" 
           type="System.Web.Handlers.TransferRequestHandler" 
           preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>

See my blog post on Dynamically Generating Robots.txt Using ASP.NET MVC for more details.




回答2:


Answer here: url with extension not getting handled by routing. Basically, when asp sees the "." it calls the static file handler, so the dynamic route is never used. The web.config files needs to be modified so /robots.txt will not be intercepted by the static file handler.



来源:https://stackoverflow.com/questions/17160744/how-to-add-route-to-dynamic-robots-txt-in-asp-net-mvc

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