ASP.NET MVC Routes with “File Extensions”

后端 未结 2 811
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 04:36

I want to make an MVC route for a list of news, which can be served in several formats.

  • news -> (X)HTML
  • news.rss -> RSS
  • news.atom -> ATOM
相关标签:
2条回答
  • 2020-12-14 05:10

    I made a method to support adding pairs like this as follows:

    public static void MapRouteWithOptionalFormat(this RouteCollection routes,
                                                  string name,
                                                  string url,
                                                  object defaults)
    {
        Route implicitRoute = routes.MapRoute(name + "-ImplicitFormat",
                                              url,
                                              defaults);
        implicitRoute.Defaults.Add("format", string.Empty);
    
        Route explicitRoute = routes.MapRoute(name + "-ExplicitFormat",
                                              url + ".{format}",
                                              defaults);
    }
    
    0 讨论(0)
  • 2020-12-14 05:11

    You can look into using constraints to make this work with normal routes.

    UPDATE: actually, I misread the question. The other answer is the correct thing to do for now. Or create a custom route. We're looking at the idea of optional segments as a possible future feature.

    0 讨论(0)
提交回复
热议问题