Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API routing and a Web API Help Page: how to avoid repeated entries

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?

like image 987
Patrick Szalapski Avatar asked Feb 10 '23 20:02

Patrick Szalapski


1 Answers

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

like image 110
Niahm Avatar answered May 01 '23 18:05

Niahm