如何从 ASP.NET Core RC2 Web Api 返回 HTTP 500? [英] How to return HTTP 500 from ASP.NET Core RC2 Web Api?

查看:25
本文介绍了如何从 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.

这篇关于如何从 ASP.NET Core RC2 Web Api 返回 HTTP 500?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆