带有"文件扩展名"的ASP.NET MVC路由

Dou*_*ean 11 asp.net-mvc

我想为一个新闻列表制作MVC路线,可以以多种格式提供.

  • 新闻 - >(X)HTML
  • news.rss - > RSS
  • news.atom - > ATOM

是否可以通过一条路线执行此操作(在我计划的设计中,在一些地方出现更为一般的"可选扩展"情况)?或者我需要制作两条这样的路线:

routes.MapRoute("News-ImplicitFormat",
                "news",
                new { controller = "News", action = "Browse", format = "" });

routes.MapRoute("News-ExplicitFormat",
                "news.{format}"
                new { controller = "News", action = "Browse" });
Run Code Online (Sandbox Code Playgroud)

似乎路由系统支持以下内容是有用的:

routes.MapRoute("News",
                "news(.{format})?",
                new { controller = "News", action = "Browse" });
Run Code Online (Sandbox Code Playgroud)

Dou*_*ean 12

我做了一个方法来支持添加如下这样的对:

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);
}
Run Code Online (Sandbox Code Playgroud)