Search code examples
.netasp.net-web-apiasp.net-web-api-routingattributerouting

How do I configure Web Api to select response format from url parameter?


I'm trying to configure web api area to allow me to pass an optional format extension. Here is my RegisterArea method's code:

public override void RegisterArea(AreaRegistrationContext context)
{
    context.Routes.MapHttpRoute(
        name: "Api_default",
        routeTemplate: @"Api/{controller}/{action}/{id}.{ext}",
        defaults: new
            {
                action = "Index",
                id = RouteParameter.Optional,
                formatter = RouteParameter.Optional
            },
        constraints: new
                            {
                                id = @"[0-9]+",
                                controller = @"[^\.]+",
                                ext = @"json|xml"
                            }
    );

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

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

}

Now, if I go to http://www.example.com/api/countries it works fine, but when I try http://www.example.com/api/countries.json gives me

No type was found that matches the controller named 'countries.json'.

What am I doing wrong?


Solution

  • Found the issue! The code above is correct. But, I'm using AttributeRouting, which added a AttributeRoutingHttpConfig.cs to my App_Start folder and was messing things up. So, if you run into this issue, check that!