c# - Web Api 如何定义具有相同参数的 2 个方法

标签 c# rest asp.net-web-api2 asp.net-web-api-routing

我是 Web API 的新手。阅读 restful 让我觉得它是基于动词的,因此我希望逻辑也是如此。

如果我想为 Delete 和 Get 创建一个 API,它们具有相同的签名,我被告知要关闭。

[HttpGet]
public HttpResponseMessage Index(int id)
{
    return Request.CreateResponse(HttpStatusCode.OK, GetValue());
}

[HttpDelete]
public HttpResponseMessage Index(int id)
{
    //logic
    return Request.CreateResponse(HttpStatusCode.OK, true);
}

我希望通过指定不同的动词 Web Api 2 来说明。但即使我将删除更新为(注意 void 返回类型)

[HttpDelete]
public void Index(int id)
{
    //logic
}

我仍然被告知具有相同参数类型的名为 index 的成员已经存在。

根据 https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client它显示

Action               HTTP method    Relative URI
Get a product by ID      GET            /api/products/id
Create a new product     POST           /api/products
Update a product         PUT            /api/products/id
Delete a product         DELETE         /api/products/id

Get、Put 和 Delete 具有相同的 URL。遗憾的是,它们不显示服务器端代码,只显示客户端。

我唯一的选择是:

1. Overload the method (in this example, seems like it would be hacking as it's not needed to perform the required task)
2. Give the method a different name (eg `Delete` instead of `Index`)

或者有别的办法吗?

最佳答案

您遇到语法问题。您可以使用属性路由来维护相同的路径,但方法必须具有不同的名称和结构,否则您将遇到您已经遇到的编译错误。

使用你问题中的例子

Action                 HTTP method    Relative URI
Get a product by ID      GET            /api/products/id
Create a new product     POST           /api/products
Update a product         PUT            /api/products/id
Delete a product         DELETE         /api/products/id

下面是一个与上面匹配的 Controller

[RoutePrefix("api/products")]
public class ProductsController : ApiController {

    [HttpGet]
    [Route("{id:int}")] //Matches GET api/products/1
    public IHttpActionResult Get(int id) {
        return Ok(GetValueById(id));
    }

    [HttpPost]
    [Route("")] //Matches POST api/products
    public IHttpActionResult Post([FromBody]Product model) {
        //...code removed for brevity
    }

    [HttpPut]
    [Route("{id:int}")] //Matches PUT api/products/1
    public IHttpActionResult Put(int id, [FromBody]Product model) {
        //...code removed for brevity
    }

    [HttpDelete]
    [Route("{id:int}")] //Matches DELETE api/products/1
    public IHttpActionResult Post(int id) {
        //...code removed for brevity
    }
}

关于c# - Web Api 如何定义具有相同参数的 2 个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44068150/

相关文章:

c# - Moq 回调不适用于 3 参数方法

java - 如何编写接受二进制文件的 Restful 网络服务 (pdf)

c# - HttpClient : This instance has already started one or more requests. 属性只能在发送第一个请求之前修改

java - 如何将对象设置为上下文,以便我可以使用 @Context 在应用程序中的任何位置获取它

javascript - jQuery 将 OPTIONS 而不是 POST 请求发送到本地主机上的 REST

Angularjs 上传 Request.Content.IsMimeMultipartContent 返回 false

post - MVC POST 请求丢失授权 header - 检索后如何使用 API 承载 token

c# - 如何避免 RCW 清理上的竞争

c# - Telerik TopPane 高度自动?

C# SSH.NET - 一个 SSH 连接与多个 SSH 连接