aspnet-core | api

ASP.NET Core - Return 500 (Internal Server Error) or any other Status Code from API

by Abhith RajanSeptember 16, 2019 · 3 min read · Last Updated:

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,

1return 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 CodeDescriptionASP.NET Core 2.2
500Internal Server ErrorStatus500InternalServerError
501Not ImplementedStatus501NotImplemented
502Bad GatewayStatus502BadGateway
503Service UnavailableStatus503ServiceUnavailable
504Gateway TimeoutStatus504GatewayTimeout
505HTTP Version Not SupportedStatus505HttpVersionNotsupported
506Variant Also NegotiatesStatus506VariantAlsoNegotiates
507Insufficient StorageStatus507InsufficientStorage
508Loop DetectedStatus508LoopDetected
510Not ExtendedStatus510NotExtended
511Network Authentication RequiredStatus511NetworkAuthenticationRequired
599Network Connect Timeout Error

You can also return some additional data along with the status code. Here is an example,

1[Route("{code}")]
2[HttpGet]
3[ProducesResponseType(typeof(Merchant), 200)]
4public async Task<ActionResult> GetMerchant(string code)
5{
6 var input = new EntityRequestDto<string>
7 {
8 Id = code
9 };
10
11 var result = await _merchantService.GetMerchant(input);
12
13 if (result.IsSuccess)
14 {
15 return Ok(result.Value);
16 }
17
18 _logger.LogError("FAILED: GetMerchant - ${result.Error}");
19 return StatusCode(StatusCodes.Status500InternalServerError, result.Error);
20
21}

If another service which is a client of the above API, they can get the additional info by,

1public async Task<MerchantPreviewDto> GetMerchant(string merchantCode)
2{
3 try
4 {
5 var merchant = await $"{_apiBaseUri}/api/v1/merchants/{merchantCode}"
6 .WithOAuthBearerToken(...)
7 .GetJsonAsync<Merchant>().ConfigureAwait(false);
8
9 return ObjectMapper.Map<MerchantPreviewDto>(merchant);
10 }
11 catch (FlurlHttpException ex)
12 {
13 var error = await ex.GetResponseStringAsync();
14 throw new UserFriendlyException("Oops! There is a problem!", error);
15 }
16}

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?

Abhith Rajan

Written by Abhith Rajan
Abhith Rajan is an aspiring software engineer with more than 7 years of experience and proven successful track record of delivering technology-based products and services.
Buy me a coffee

Was this article helpful?

Your opinion matters

Please share your thought about this article

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub

Related Posts

Related Videos

Related Services

Flurl

Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library for .NET.

HTTP Status Codes — httpstatuses.com

HTTP Status Code directory, with definitions, details and helpful code references.