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

时间:2017-05-19 10:50:12

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

我是Web API的新手。阅读宁静使我认为这是基于动词,因此我希望逻辑也是如此。

如果我想创建一个删除和获取的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://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`)

还是有另一种方式吗?

2 个答案:

答案 0 :(得分:1)

您可以在api方法上使用Route属性,请查看以下内容:

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

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

设置http方法获取get请求并删除删除请求,类似于post / put。

enter image description here

enter image description here

enter image description here

enter image description here

答案 1 :(得分:1)

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

使用您问题中的示例

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