且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC路由与"文件扩展名"

更新时间:2022-10-17 07:46:30

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

 公共静态无效MapRouteWithOptionalFormat(这RouteCollection路线,
                                              字符串名称,
                                              字符串的URL,
                                              对象的默认值)
{
    路线implicitRoute = routes.MapRoute(名称+-ImplicitFormat
                                          URL,
                                          默认值);
    implicitRoute.Defaults.Add(格式的String.Empty);    路线explicitRoute = routes.MapRoute(名称+-ExplicitFormat
                                          网址+。{}格式,
                                          默认值);
}

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

Is it possible to do this (the more general "optional extension" situation crops up in several places in my planned design) with one route? Or do I need to make two routes like this:

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

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

It seems like it would be useful to have the routing system support something like:

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

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);
}