在RC1中,我会这样做:

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

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

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


当前回答

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

return StatusCode(StatusCodes.Status500InternalServerError, responseObject);

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

其他回答

如果你不希望硬编码特定的数字,你可以使用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);

对于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);
}

如何创建一个自定义ObjectResult类,表示一个内部服务器错误,就像一个OkObjectResult? 您可以在自己的基类中放置一个简单的方法,这样您就可以轻松地生成InternalServerError并返回它,就像您做Ok()或BadRequest()一样。

[Route("api/[controller]")]
[ApiController]
public class MyController : MyControllerBase
{
    [HttpGet]
    [Route("{key}")]
    public IActionResult Get(int key)
    {
        try
        {
            //do something that fails
        }
        catch (Exception e)
        {
            LogException(e);
            return InternalServerError();
        }
    }
}

public class MyControllerBase : ControllerBase
{
    public InternalServerErrorObjectResult InternalServerError()
    {
        return new InternalServerErrorObjectResult();
    }

    public InternalServerErrorObjectResult InternalServerError(object value)
    {
        return new InternalServerErrorObjectResult(value);
    }
}

public class InternalServerErrorObjectResult : ObjectResult
{
    public InternalServerErrorObjectResult(object value) : base(value)
    {
        StatusCode = StatusCodes.Status500InternalServerError;
    }

    public InternalServerErrorObjectResult() : this(null)
    {
        StatusCode = StatusCodes.Status500InternalServerError;
    }
}

从我所看到的ControllerBase类中有helper方法。只需使用StatusCode方法:

[HttpPost]
public IActionResult Post([FromBody] string something)
{    
    //...
    try
    {
        DoSomething();
    }
    catch(Exception e)
    {
         LogException(e);
         return StatusCode(500);
    }
}

你也可以使用StatusCode重载(int StatusCode, object value)来协商内容。

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