2016-06-13 88 views
56

,我這樣做:如何從ASP.NET Core RC2 Web Api返回HTTP 500?早在RC1

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

在RC2,也不再是HttpStatusCodeResult,並沒有什麼我能找到讓我回到一個500型IActionResult的。

現在的方法與我所要求的完全不同嗎?我們不再試圖在Controller代碼中捕獲嗎?我們只是讓框架拋出一個通用的500異常回API調用者?對於開發,我怎麼能看到確切的異常棧?

回答

70

從我可以看到ControllerBase類中有幫助方法。只需使用StatusCode方法:

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

您也可以使用StatusCode(int statusCode, object value)超載也協商的內容。

2

你可以返回BadRequestResult或StatusCodeResult,即:

return new BadRequestResult(); 

return new StatusCodeResult(500) 
+24

錯誤的請求是HTTP代碼400和客戶端發送無效請求/數據(即失敗的模型驗證)的信號。 http代碼500是針對內部服務器錯誤,不完全一樣;) – Tseng

+0

啊,謝謝!我不確定BadRequest是什麼,這是有道理的 –

35

你可以使用Microsoft.AspNetCore.Mvc.ControllerBase.StatusCodeMicrosoft.AspNetCore.Http.StatusCodes形成你的反應,如果你不希望特定硬編碼數字。

return StatusCode(StatusCodes.Status500InternalServerError); 
+2

偉大的,避免任何硬編碼的部分/「幻數」。我之前使用過StatusCode((int)HttpStatusCode.InternalServerError),但我更喜歡你的。 – aleor

+1

我當時沒有考慮的一件事是,它使代碼更具可讀性,回到代碼中,您知道錯誤號500與哪個代碼相關。自我記錄:-) –

+2

我無法想象內部服務器錯誤(500)很快就會改變。 – rolls

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

應該被使用。

HttpStatusCode是在System.Net枚舉。

3

一種更好的方式來處理這種截至目前(1.1)是爲此在Startup.csConfigure()

app.UseExceptionHandler("/Error"); 

這將執行對/Error的路線。這樣可以節省您爲您編寫的每個操作添加try-catch塊。

當然,你需要一個類似於ErrorController添加到此:

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

更多信息here


在你想獲得實際的異常數據的情況下,你可能會在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's blog

+0

這太棒了,但我怎麼能記錄引發的異常? – redwards510

+0

@ redwards510下面是你如何做到這一點:https://scottsauber.com/2017/04/03/adding-global-error-handling-and-logging-in-asp-net-core/我會更新我的答案反映它,因爲這是一個非常常見的用例 – gldraphael

-2
return StatusCodes.Status500InternalServerError; 
+2

您不能返回枚舉,它需要包裝在StatusCode方法中 - 就像其他人在幾個月前發佈的那樣。 – McGuireV10

相關問題