ASP.NET MVC路由与"文件扩展名" [英] ASP.NET MVC Routes with "File Extensions"
本文介绍了ASP.NET MVC路由与"文件扩展名"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想打一个MVC路线的新闻列表,可以在多种格式送达。
- 新闻中心 - >(X)HTML
- news.rss - > RSS
- news.atom - > ATOM
是否有可能做到这一点(更普遍的可选扩展的情况在好几个地方在我的计划中设计了作物)一个路线?或做我需要做这样的两条路线:
routes.MapRoute(新闻ImplicitFormat
新闻,
新{控制器=新闻,行动=浏览,格式=});routes.MapRoute(新闻ExplicitFormat
的新闻。{}格式
新{控制器=新闻,行动=浏览});
看起来这将是非常有用的路由系统的支持是这样的:
routes.MapRoute(新闻报,
新闻({}格式)?
新{控制器=新闻,行动=浏览});
解决方案
我做了一个方法来支持添加对这样如下:
公共静态无效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);
}
这篇关于ASP.NET MVC路由与"文件扩展名"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文