4

I am getting repeat entries rendered in my Web API Help Page with different parents, such as these, that refer to the same method:

GET api/{apiVersion}/v1/Products - Gets all products

...

GET api/v1/Products - Gets all products

...

I have a Web API page with some routing like this:

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

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

I had thought that this routing would make the "v1" optional, so the derived documentation above is not expected.

(sidebar: Going to api/products certainly doesn't work, so I am not sure what is wrong with this. What am I missing?)

It seems the real problem is that Web API Help Page is reading the routes improperly, as I thought v1 and {apiVersion} should not both appear in the same action. What am I missing here?

Community
  • 1
  • 1
Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129
  • Potential duplicate: http://stackoverflow.com/questions/13394993/net-web-api-help-page-showing-two-versions-of-every-method – Zee Mar 11 '15 at 16:33
  • I don't think it is a duplicate--the first entry in my post, as it shows up, seems simply to be wrong. No URL with that structure will work, per the routing at the bottom of my post. – Patrick Szalapski Mar 11 '15 at 20:57

2 Answers2

6

Try using Attribute Routing, install nuget package

Install-Package Microsoft.AspNet.WebApi.WebHost

Enable Attribute Routing in the WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

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

Then use the attribute Route in the methods of your Controller

[Route("~/api/v1/Products")]
[HttpGet]
public List<Product> Products()
{}

[Route("~/api/v2/Products")]
[HttpGet]
public List<Product> V2Products()
{}

in the documentation you will get

GET api/v1/Products - Gets all products

GET api/v2/Products - Gets all products

Community
  • 1
  • 1
Niahm
  • 424
  • 5
  • 11
2

It seems like this is a shortcoming of the ASP.NET Web API help pages. To workaround, I changed the view to exclude these invalid routes from the rendered document. For the above example, I added this Where clause to the loop in ApiGroup.cshtml, changing

@foreach (var api in Model){

to

@foreach (var api in Model.Where(m => !m.Route.RouteTemplate.Contains(@"{apiVersion}"))){
Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129