UriPathExtensionMapping to control response format in WebAPI

和自甴很熟 提交于 2019-12-03 08:52:09

问题


I'm having a problem getting UriPathExtensionMapping working in ASP.NET WebAPI. My setup is as follows:

My routes are:

            config.Routes.MapHttpRoute(
                name: "Api UriPathExtension",
                routeTemplate: "api/{controller}.{extension}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
               name: "Api UriPathExtension ID",
                routeTemplate: "api/{controller}/{id}.{extension}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

My Global ASAX file is:

    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

My Controller is:

public IEnumerable<string> Get()
{
    return new string[] { "Box", "Rectangle" };
}

// GET /api/values/5
public string Get(int id)
{
    return "Box";
}

// POST /api/values
public void Post(string value)
{
}

// PUT /api/values/5
public void Put(int id, string value)
{
}

// DELETE /api/values/5
public void Delete(int id)
{
}

When making requests using curl, JSON is the default response, even when I explicitly request XML I still get JSON:

curl http://localhost/eco/api/products/5.xml

Returns:

"http://www.google.com"

Can anyone see the problem with my setup?

The following code maps the extensions in the Global.asax file after the routes have been configured:

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.
        MediaTypeMappings.Add(
            new UriPathExtensionMapping(
                "json", "application/json"
        )
    );

    GlobalConfiguration.Configuration.Formatters.XmlFormatter.
        MediaTypeMappings.Add(
            new UriPathExtensionMapping(
                "xml", "application/xml"
        )
    );

回答1:


Do you need to register the extension mapping like so:

config.Formatters.JsonFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("json", "application/json"));
config.Formatters.XmlFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("xml", "application/xml"));

Example was found here.

Update

If you look at the code for UriPathExtensionMapping the placeholder for the extension is

/// <summary>
/// The <see cref="T:System.Uri"/> path extension key.
/// </summary>
public static readonly string UriPathExtensionKey = "ext";

So your routes would need to be changed to ({ext} not {extension}):

config.Routes.MapHttpRoute(
            name: "Api UriPathExtension",
            routeTemplate: "api/{controller}.{ext}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );



回答2:


As an addendum to this answer, because I can't comment yet, you should also make sure your web.config contains the line

<modules runAllManagedModulesForAllRequests="true" />

inside the <system.webServer> section.

Mine didn't and this example didn't work for me until I added that line.



来源:https://stackoverflow.com/questions/14728152/uripathextensionmapping-to-control-response-format-in-webapi

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