SoftwareNerd
SoftwareNerd

Reputation: 1905

Route Static URL to Controller action in MVC?

Hi all i have an aciton in my controller which generates an sitemap for my site, the problem here is for the first time when the file not exists the request goes to the action but once the file is generated , a static file is placed in the site , after that when i hit the URL the request is not going to the controller , is there a fix for this

Below is the URL

        http://localhost:1234/sitemap.xml

Below is the code am using

        [HttpGet, ActionName("sitemap")]
        public ActionResult sitemap()
        {           

           //will get the sitemap content here and will generate the sitemap 
            var sitemapFile = "~/sitemap.xml";
            return File(sitemapFile, "text/xml");
        }

Every time i hit the URL it should go to the action and regenerate the file , but this is not working here can any one help me out

Upvotes: 2

Views: 1626

Answers (2)

Andrew
Andrew

Reputation: 5440

When your sitemap.xml file exists IIS will pick up the request and serve your existing sitemap.xml. For more information on this matter, take a look at this article

If I understand correctly you want to route sitemap.xml requests to a MVC route, here is good blog post about that.

What you need to do first is to map the request of the sitemap.xml to the TransferRequestHandler. Add this to your web.config

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

Next configure the route in your RouteConfig.cs:

routes.MapRoute(
    name: "SiteMapRoute",
    url: "sitemap.xml",
    defaults: new { controller = "SEO", action = "Sitemap", page = UrlParameter.Optional }
);

And put this statement before you map any route

routes.RouteExistingFiles = true;

More information on RouteExistingFiles

Upvotes: 2

shammelburg
shammelburg

Reputation: 7328

Could you try this custom route please,

Add it to your RouteConfig.cs file

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

You can access your Action like this,

http://localhost:1234/sitemap

Hope its what you're looking for.

Upvotes: 1

Related Questions