Web Api 如何定义两个具有相同参数的方法

Web Api how to define 2 methods with same parameters

我是网络新手 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 return 类型)

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

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

根据https://docs.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`)

或者有别的方法吗?

您可以在 api 方法上使用 Route 属性,检查如下:

[HttpGet]
    [Route("same")]
    public IHttpActionResult get(int id)
    {
        return Ok();
    }

    [HttpDelete]
    [Route("same")]
    public IHttpActionResult delete(int id)
    {
        return Ok();
    }

并设置http方法get请求get,delete请求delete,类似post/put。

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

使用您问题中的示例

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

下面是与上面匹配的控制器

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