在RC1中,我会这样做:

[HttpPost]
public IActionResult Post([FromBody]string something)
{    
    try{
        // ...
    }
    catch(Exception e)
    {
         return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
    }
}

在RC2中,不再有HttpStatusCodeResult,也没有什么我可以找到,让我返回一个500类型的IActionResult。

现在的方法与我要求的完全不同吗?我们在控制器代码中不再尝试捕获了吗?我们只是让框架向API调用者抛出一个通用的500异常吗?对于开发,我如何才能看到确切的异常堆栈?


当前回答

当你想在MVC .Net Core中返回JSON响应时,你也可以使用:

Response.StatusCode = (int)HttpStatusCode.InternalServerError;//Equals to HTTPResponse 500
return Json(new { responseText = "my error" });

这将返回JSON结果和HTTPStatus。我用它来返回结果到jQuery.ajax()。

其他回答

目前(1.1)更好的处理方法是在Startup.cs的Configure()中执行:

app.UseExceptionHandler("/Error");

这将执行/Error的路由。这将使您不必为编写的每个操作添加try-catch块。

当然,你需要添加一个类似这样的ErrorController:

[Route("[controller]")]
public class ErrorController : Controller
{
    [Route("")]
    [AllowAnonymous]
    public IActionResult Get()
    {
        return StatusCode(StatusCodes.Status500InternalServerError);
    }
}

更多信息请点击这里。


如果您想要获得实际的异常数据,可以在return语句之前将其添加到上面的get()中。

// Get the details of the exception that occurred
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

if (exceptionFeature != null)
{
    // Get which route the exception occurred at
    string routeWhereExceptionOccurred = exceptionFeature.Path;

    // Get the exception that occurred
    Exception exceptionThatOccurred = exceptionFeature.Error;

    // TODO: Do something with the exception
    // Log it with Serilog?
    // Send an e-mail, text, fax, or carrier pidgeon?  Maybe all of the above?
    // Whatever you do, be careful to catch any exceptions, otherwise you'll end up with a blank page and throwing a 500
}

以上片段摘自Scott Sauber的博客。

当你想在MVC .Net Core中返回JSON响应时,你也可以使用:

Response.StatusCode = (int)HttpStatusCode.InternalServerError;//Equals to HTTPResponse 500
return Json(new { responseText = "my error" });

这将返回JSON结果和HTTPStatus。我用它来返回结果到jQuery.ajax()。

return StatusCode((int)HttpStatusCode.InternalServerError, e);

应用于非asp。NET上下文(参见ASP. NET上下文的其他答案)。网络核心)。

HttpStatusCode是System.Net中的一个枚举。

如果你需要一个人来回应,你可以打电话

return StatusCode(StatusCodes.Status500InternalServerError, responseObject);

这将返回一个500和响应对象…

Microsoft.AspNetCore.Mvc的内置Problem()方法将返回一个基于RFC 7807的“问题细节”响应。NET Core 3.0及更高版本)。只要没有显式地设置其他状态,它将始终返回状态代码500。

[HttpPost]
public IActionResult Post([FromBody] string value)
{
    try
    {
        // ...
    }
    catch (Exception ex)
    {
        return Problem(
            //all parameters are optional:
            //detail: "Error while processing posted data."; //an explanation, ex.Stacktrace, ...
            //instance: "/city/London"  //A reference that identifies the specific occurrence of the problem
            //title: "An error occured." //a short title, maybe ex.Message
            //statusCode: StatusCodes.Status504GatewayTimeout, //will always return code 500 if not explicitly set
            //type: "http://example.com/errors/error-123-details"  //a reference to more information
            );
    }           
}

如果不设置任何参数,它将返回:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.6.1",
    "title": "An error occured while processing your request.",
    "status": 500,
    "traceId": "|fadaed95-4d06eb16160e4996."
}

有关“问题详细信息”参数的更多信息: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails?view=aspnetcore-5.0