我有一个ASP.NET Core 1.0 Web API应用程序,并试图弄清楚如果我的控制器正在调用的函数出错,如何将异常消息传递给客户端.
我试了那么多东西,但没有一样能做到IActionResult
.
我不明白为什么这不是人们需要的普通东西.如果真的没有解决办法,谁能告诉我为什么?
我确实看到一些使用HttpResponseException(HttpResponseMessage)
的文档,但为了使用它,我必须安装compat垫片.在Core1.0中有没有一种新的方法来做这些事情?
以下是我一直在try 的垫片,但它不起作用:
// GET: api/customers/{id}
[HttpGet("{id}", Name = "GetCustomer")]
public IActionResult GetById(int id)
{
Customer c = _customersService.GetCustomerById(id);
if (c == null)
{
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("Customer doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound
};
throw new HttpResponseException(response);
//return NotFound();
}
return new ObjectResult(c);
}
当抛出HttpResponseException
时,我查看客户端,在内容中找不到我正在发送的消息.