我是 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 的成员已经存在。
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/