Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 767
JSS Avatar asked Jun 18 '13 04:06

JSS


People also ask

Which method is used for adding routes to an MVC application?

When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table. The default route table contains a single route (named Default).

What is dynamic routing in MVC?

What is Dynamic Routing? MVC Routing operates on the basis that a request is handled by Controllers and Actions in predefined routes. Dynamic Routing is where a request maps to a Page (TreeNode), and that Page's settings (Template, Page Type) determines how the request should be handled (which Controller/Action/View).

What is routes MapRoute in MVC?

routes. MapRoute has attributes like name, url and defaults like controller name, action and id (optional). Now let us create one MVC Application and open RouteConfig. cs file and add the following custom route.

Can we add constraints to the route in MVC?

Attribute Routing is introduced in MVC 5.0. We can also define parameter constraints by placing a constraint name after the parameter name separated by a colon. There are many builtin routing constraints available. We can also create custom routing constraints.


2 Answers

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.

like image 150
Muhammad Rehan Saeed Avatar answered Sep 28 '22 02:09

Muhammad Rehan Saeed


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.

like image 40
JSS Avatar answered Sep 28 '22 01:09

JSS