ASP.NET Core - Return 500 (Internal Server Error) or any other Status Code from API
A good REST API will respond with proper HTTP status codes. In ASP.NET Core, returning status code is easier than you might think.
commit 6e94f2d · authored · amended · 2 min read
HTTP response status codes have so much importance in REST API’s. In any case if you want to return a status code from your ASP.NET Core API, all you have to do is in your controller method,
return StatusCode(StatusCodes.Status500InternalServerError);StatusCode is from Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode and StatusCodes from Microsoft.AspNetCore.Http.StatusCodes. The above code will return a 500 status code. Similar way, you can return any other status code. For the complete list,
👉 StatusCodes Class (Microsoft.AspNetCore.Http) | Microsoft Docs
HTTP status code 5xx indicates server error. 5xx series includes,
| Status Code | Description | ASP.NET Core 2.2 |
|---|---|---|
| 500 | Internal Server Error | Status500InternalServerError |
| 501 | Not Implemented | Status501NotImplemented |
| 502 | Bad Gateway | Status502BadGateway |
| 503 | Service Unavailable | Status503ServiceUnavailable |
| 504 | Gateway Timeout | Status504GatewayTimeout |
| 505 | HTTP Version Not Supported | Status505HttpVersionNotsupported |
| 506 | Variant Also Negotiates | Status506VariantAlsoNegotiates |
| 507 | Insufficient Storage | Status507InsufficientStorage |
| 508 | Loop Detected | Status508LoopDetected |
| 510 | Not Extended | Status510NotExtended |
| 511 | Network Authentication Required | Status511NetworkAuthenticationRequired |
| 599 | Network Connect Timeout Error |
You can also return some additional data along with the status code. Here is an example,
[Route("{code}")][HttpGet][ProducesResponseType(typeof(Merchant), 200)]public async Task<ActionResult> GetMerchant(string code){ var input = new EntityRequestDto<string> { Id = code };
var result = await _merchantService.GetMerchant(input);
if (result.IsSuccess) { return Ok(result.Value); }
_logger.LogError("FAILED: GetMerchant - ${result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, result.Error);
}If another service which is a client of the above API, they can get the additional info by,
public async Task<MerchantPreviewDto> GetMerchant(string merchantCode){ try { var merchant = await $"{_apiBaseUri}/api/v1/merchants/{merchantCode}" .WithOAuthBearerToken(...) .GetJsonAsync<Merchant>().ConfigureAwait(false);
return ObjectMapper.Map<MerchantPreviewDto>(merchant); } catch (FlurlHttpException ex) { var error = await ex.GetResponseStringAsync(); throw new UserFriendlyException("Oops! There is a problem!", error); }}Bonus
On the client service, I am using Flurl, which is my favorite HTTP client.
Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library for .NET.
Which one is your favorite HTTP client library for .NET?