如何从 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.