0

I'm trying to get a handle on attribute routing in MVC.

Initially, the routing for my sitemap controller was as follows:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "SitemapXml",
            url: "sitemap.xml",
            defaults: new { controller = "Sitemap", action = "Index" }

        // Additional mappings...

    }
}

That works fine. But then I tried commenting out the SitemapXml routing above and instead adding an attribute in my controller.

// GET: Sitemap
[Route("sitemap.xml")]
public ActionResult Index()
{
    // Generate sitemap
}

I also added the following line at the end of RegisterRoutes:

routes.MapMvcAttributeRoutes();

But now when I navigate to domain.com/sitemap.xml, I get a page not found error.

Questions:

  1. What steps am I missing to get my routing attribute to work?
  2. Since mappings can now be specified in two places (as attributes or set directly in the RouteCollection), what happens when those two places contradict each other?
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • 2
    It is the `.` in the URL. Did you see https://stackoverflow.com/questions/11728846/dots-in-url-causes-404-with-asp-net-mvc-and-iis ? – Shyju Nov 24 '18 at 21:15
  • @Shyju: I didn't see that. Thanks, I didn't realize the dot causes problems. Looks like the workaround isn't that great either. Guess I'll just go back to setting that in `RegisterRoutes`. (It doesn't appear to have any problem with dots.) – Jonathan Wood Nov 24 '18 at 21:19

1 Answers1

0

if you remove the extension .xml , your attribute routing will work perfectly. And its better to use the extension related code in action method.

Also make sure your route config looke like (routes.MapMvcAttributeRoutes(); should exist before default route)

routes.MapMvcAttributeRoutes();
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
    );
pfx
  • 20,323
  • 43
  • 37
  • 57