Web API:具有不同HTTP动词的相同方法 [英] Web API: Same Method with different HTTP Verbs

查看:68
本文介绍了Web API:具有不同HTTP动词的相同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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:消息":发生错误.","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检测到潜在的模棱两可的路由时,就会出现该错误.歧义路由是返回多于一种资源类型的单个路由(基本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:

  1. GET/apples//返回苹果列表
  2. GET/apples?type = red//返回红色苹果列表

错误的方式:

  1. GET/apples///返回苹果列表
  2. 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:

  1. 请确保您使用单一资源类型表示单个路由(基本URI).
  2. 如果您必须用不同的类型来表示一条路由(通常是个坏主意),则可以通过在违规方法中添加以下属性来忽略使文档含糊不清的路由

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

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

希望这会有所帮助.

这篇关于Web API:具有不同HTTP动词的相同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆