Web API:使用不同 HTTP 动词的相同方法动词、不同、方法、Web

2023-09-08 09:21:43 作者:旁观者

在一个 WEB API 控制器中,我们可以用不同的 HTTP 动词有相同的方法名吗?

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

  [HttpGet]
        public string Test()
        {
            return "Success Get";
        }


  [HttpPost]
        public string Test(int i)
        {
            return "Success Post";
        }

Swagger 不接受此配置.访问 API 方法时出现此错误:

Swagger does not accept this configuration. I get this error when accessing the API methods:

500 : "Message":"发生错误.","ExceptionMessage":"Swagger 2.0 不支持:路径为 'api/Common' 和方法为 'POST' 的多个操作.请参阅配置设置 - "ResolveConflictingActions" 寻找潜在的解决方法"

500 : "Message":"An error has occurred.","ExceptionMessage":"Not supported by Swagger 2.0: Multiple operations with path 'api/Common' and method 'POST'. See the config setting - "ResolveConflictingActions" for a potential workaround"

这是我的routeconfig:

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

            config.Routes.MapHttpRoute(
                name: "DefaultApiByAction",
                routeTemplate: "api/{controller}/{action}"
                );

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

推荐答案

方法名本身对 Swagger 无关紧要,路由才是.当 Swagger 检测到可能不明确的路线时,它会因该错误而崩溃.不明确的路由是返回超过 1 种资源类型的单个路由(基本 uri).出于某种疯狂的原因,Microsoft Web Api 允许您为相同的 URI 返回不同的资源,这就是您遇到尝试使用您的 API(和 Swagger)的人的麻烦.

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).

单个 URI 应代表单个资源.正确方法:

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

GET/apples//返回一个苹果列表GET/apples?type=red//返回一个红苹果列表

错误的方式:

GET/apples///返回一个苹果列表GET/apples?type=red//返回自卸车

Microsoft Web Api 允许您使用多种方法处理单个路由,因此您冒着意外创建模糊路由的非常严重的风险.

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.

会破坏 Swagger 的代码示例:

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?!
}

许多 Swagger 框架在运行时扫描您的代码并创建一个 Swagger 2.0 JSON 文档.Swagger UI 请求该 JSON 文档并基于该文档构建您看到的 UI.现在因为 Swagger 框架正在扫描您的代码以构建 JSON,如果它看到两个方法代表返回不同类型的单个资源并且它会中断.发生这种情况是因为 Swagger 不知道如何表示该 URI,因为它不明确.

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:

确保您使用单一资源类型表示单一路由(基本 URI).

如果您必须用不同类型表示单个路由(通常是个坏主意),那么您可以通过将以下属性添加到违规方法来忽略使文档模棱两可的路由 Make sure that you are representing a single route (base URI) with a single resource type. Js web Api

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)]

[ApiExplorerSettings(IgnoreApi = true)]

这将告诉文档在记录 API 时完全忽略此方法,并且 Swagger 将呈现.请记住,如果您使用 #2,那么 Swagger 将不会呈现此方法,这可能会给使用您的 API 的人带来问题.

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.

希望这会有所帮助.

 
精彩推荐
图片推荐