ASP.NET MVC Routes with “File Extensions”

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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

回答1:

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


回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!