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

空扰寡人 提交于 2019-12-22 08:57:53

问题


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?


回答1:


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




回答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}"))){


来源:https://stackoverflow.com/questions/28730307/web-api-routing-and-a-web-api-help-page-how-to-avoid-repeated-entries

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