在RC1中,我会这样做:
[HttpPost]
public IActionResult Post([FromBody]string something)
{
try{
// ...
}
catch(Exception e)
{
return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
}
}
在RC2中,不再有HttpStatusCodeResult,也没有什么我可以找到,让我返回一个500类型的IActionResult。
现在的方法与我要求的完全不同吗?我们在控制器代码中不再尝试捕获了吗?我们只是让框架向API调用者抛出一个通用的500异常吗?对于开发,我如何才能看到确切的异常堆栈?
对于aspnetcore-3.1,你也可以像下面这样使用Problem();
https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1
[Route("/error-local-development")]
public IActionResult ErrorLocalDevelopment(
[FromServices] IWebHostEnvironment webHostEnvironment)
{
if (webHostEnvironment.EnvironmentName != "Development")
{
throw new InvalidOperationException(
"This shouldn't be invoked in non-development environments.");
}
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message);
}
对于aspnetcore-3.1,你也可以像下面这样使用Problem();
https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1
[Route("/error-local-development")]
public IActionResult ErrorLocalDevelopment(
[FromServices] IWebHostEnvironment webHostEnvironment)
{
if (webHostEnvironment.EnvironmentName != "Development")
{
throw new InvalidOperationException(
"This shouldn't be invoked in non-development environments.");
}
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message);
}
如果你不希望硬编码特定的数字,你可以使用Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode和microsoft . aspnetcore . http . statuscode来形成你的响应。
return StatusCode(StatusCodes.Status500InternalServerError);
更新:2019年8月
也许与最初的问题没有直接关系,但当试图用Microsoft Azure函数实现相同的结果时,我发现我必须在Microsoft. aspnetcore . mvc . core程序集中构造一个新的StatusCodeResult对象。我的代码现在是这样的;
return new StatusCodeResult(StatusCodes.Status500InternalServerError);