首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在MVC4中扩展内容协商行为?

如何在MVC4中扩展内容协商行为?
EN

Stack Overflow用户
提问于 2012-03-14 13:10:47
回答 1查看 1.4K关注 0票数 4

我正在研究RESTful API的设计,以及我向程序员StackExchange站点here发布的关于内容协商的问题之一。

基于此,我感兴趣的是如何在MVC4中支持以下行为:

如果在application.json.上指定了扩展(例如,GET /api/search.json/api/search.xml),则重写MVC4

  • 中的默认内容协商行为(如果没有指定扩展),则使用检查application/xml/api/search.xml的接受标头值的默认行为

捕获这个扩展和修改内容协商行为的最干净/最直接的方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-14 16:25:17

您可以使用格式化程序中的UriPathExtensionMapping来完成这一任务。这些映射允许您为格式化程序“分配”一个扩展,以便在内容协商期间给予它们优先权。您还需要添加一个路由,以便具有"extension“的请求也被接受。下面的代码显示默认模板中启用此方案所需的更改。

代码语言:javascript
复制
    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();
    }
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9702659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档