Web API: Same Method with different HTTP Verbs

后端 未结 4 633
鱼传尺愫
鱼传尺愫 2021-01-06 12:48

In a WEB API controller, can we have the same method name with different HTTP Verbs?

  [HttpGet]
        public string Test()
        {
            return \"         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 13:27

    The method names themselves don't matter to Swagger, the routes do. Swagger will blow up with that error when it detects potentially ambiguous routes. An ambiguous route being a single route (base uri) that returns more than 1 type of resource. For some crazy reason, Microsoft Web Api allows you to return different resources for the same URI and this is where you get into trouble with people trying to consume your API (and Swagger).

    A single URI should represent a single resource.
    Correct way:

    1. GET /apples // returns a list of apples
    2. GET /apples?type=red // returns a list of red apples

    Incorrect way:

    1. GET /apples/ // Return a list of apples
    2. GET /apples?type=red // returns a dump truck

    Microsoft Web Api allows you to handle a single route with multiple methods and because of this you run a very serious risk of accidentally creating an ambiguous route.

    Example of code that will break Swagger:

    [HttpGet, Route("apples")]
    public HttpResponseMessage GetApples()
    {
        return _productRepository.Get(id);
    }
    
    [HttpGet, Route("apples")]
    pblic HttpResponseMessage GetApples([FromUri]string foo)
    {
        return new DumpTruck(); // Say WHAAAAAAT?!
    }
    

    A lot of Swagger frameworks scan your code at runtime and create a Swagger 2.0 JSON document. The Swagger UI requests that JSON document and builds the UI that you see based on that document.
    Now because the Swagger framework is scanning your code to build the JSON, if it sees two methods that represent a single resource that return different types and it breaks. This happens because Swagger does not know how to represent that URI because it is ambiguous.

    Here are some things you can do to help solve this problem:

    1. Make sure that you are representing a single route (base URI) with a single resource type.
    2. If you HAVE to represent a single route with different types (typically a bad idea), then you can ignore routes that make the documentation ambiguous by adding the following attribute to the offending method

      [ApiExplorerSettings(IgnoreApi = true)]

    This will tell the documentation to ignore this method completely when documenting the API and Swagger will render. Remember that if you are using #2 then Swagger will NOT render this method which can cause problems for people consuming your APIs.

    Hope this helps.

提交回复
热议问题