我正在研究RESTful API的设计,以及我向程序员StackExchange站点here发布的关于内容协商的问题之一。
基于此,我感兴趣的是如何在MVC4中支持以下行为:
如果在application.json.上指定了扩展(例如,GET /api/search.json或/api/search.xml),则重写MVC4
application/xml或/api/search.xml的接受标头值的默认行为捕获这个扩展和修改内容协商行为的最干净/最直接的方法是什么?
发布于 2012-03-14 16:25:17
您可以使用格式化程序中的UriPathExtensionMapping来完成这一任务。这些映射允许您为格式化程序“分配”一个扩展,以便在内容协商期间给予它们优先权。您还需要添加一个路由,以便具有"extension“的请求也被接受。下面的代码显示默认模板中启用此方案所需的更改。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "Api with extension",
routeTemplate: "api/{controller}.{ext}/{id}",
defaults: new { id = RouteParameter.Optional, ext = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
GlobalConfiguration.Configuration.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
BundleTable.Bundles.RegisterTemplateBundles();
}https://stackoverflow.com/questions/9702659
复制相似问题