【发布时间】:2016-02-26 19:38:05
【问题描述】:
我的 API 控制器 (MVC5) 中有这 2 个 API:
[HttpGet]
[HttpPost]
public RestErrorHandler Add([FromBody]Models.Customer customer)
{
try
{
//do something...
return new RestErrorHandler { Error = res.ErrorMessage, Location = MethodBase.GetCurrentMethod().Name };
}
catch (Exception ex)
{
return new RestErrorHandler { Error = ex.ToString(), Location = MethodBase.GetCurrentMethod().Name };
}
}
[HttpGet]
[HttpPost]
public RestErrorHandler Delete([FromBody]Models.Customer customer)
{
try
{
//do something
return new RestErrorHandler { Error = res.ErrorMessage, Location = MethodBase.GetCurrentMethod().Name };
}
catch (Exception ex)
{
return new RestErrorHandler { Error = ex.ToString(), Location = MethodBase.GetCurrentMethod().Name };
}
}
我的客户电话是这样的:
var response = client.PostAsync(string.Format("http://my_uri/api/Customer/" + action), contentPost).Result;
其中“操作”可以是“添加”或“删除”。
测试删除它告诉我这个错误:
Multiple actions were found that match the request:
为了尝试“强制”它以正确的方式运行,我在 API 中的方法中添加了一个 Route 标记:
[HttpGet]
[HttpPost]
[Route("Customer/Delete/Customer")]
public RestErrorHandler Delete([FromBody]Models.Customer customer)
{
try
{
//do something
return new RestErrorHandler { Error = res.ErrorMessage, Location = MethodBase.GetCurrentMethod().Name };
}
catch (Exception ex)
{
return new RestErrorHandler { Error = ex.ToString(), Location = MethodBase.GetCurrentMethod().Name };
}
}
但它调用我的“添加”api..?
请问我错过了什么?
【问题讨论】:
-
您不应该在同一方法上使用 get 和 post。
-
@StephenBrickner 如果我从 api 返回一些东西,我还需要使用 get。否则它不起作用..
-
它可以在不使用 GET 的情况下工作。
-
@StephenBrickner 我现在正在发布和测试。谢谢:)
-
没问题,希望对你有帮助。
标签: c# routes asp.net-web-api2