如何从ASP.NET Core RC2 Web Api返回HTTP 500?
回到RC1,我会这样做:
Back in RC1, I would do this:
[HttpPost]
public IActionResult Post([FromBody]string something)
{
try{
// ...
}
catch(Exception e)
{
return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
}
}
在RC2中,不再有HttpStatusCodeResult,而且找不到让我返回500类型的IActionResult的任何东西.
In RC2, there no longer is HttpStatusCodeResult, and there is nothing I can find that lets me return a 500 type of IActionResult.
对于我要问的问题,现在的方法是否完全不同?我们是否不再尝试在Controller
代码中捕获?我们是否只是让框架向API调用者抛出泛型500异常?对于开发,如何查看确切的异常堆栈?
Is the approach now entirely different for what I'm asking? Do we no longer try-catch in Controller
code? Do we just let the framework throw a generic 500 exception back to the API caller? For development, how can I see the exact exception stack?
据我所见,ControllerBase
类内部有帮助方法.只需使用StatusCode
方法:
From what I can see there are helper methods inside the ControllerBase
class. Just use the StatusCode
method:
[HttpPost]
public IActionResult Post([FromBody] string something)
{
//...
try
{
DoSomething();
}
catch(Exception e)
{
LogException(e);
return StatusCode(500);
}
}
您还可以使用StatusCode(int statusCode, object value)
重载来协商内容.
You may also use the StatusCode(int statusCode, object value)
overload which also negotiates the content.