Search code examples
asp.net-web-apiasp.net-web-api-routing

UriPathExtensionMapping to control response format in WebAPI


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

Solution

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