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

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

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 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,

[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?

local graph · open full graph

"ASP.NET Core - Return 500 (Internal Server Error) or any other Status Code from API" is connected to the topics ASP.NET Core, API and related to 6 other entries. .NET Core API Gateway Ocelot - Logging HTTP Requests & Response Including Headers & Body .NET Core API Gateway Ocelo… ASP.NET Core - OAuth 2.0 Client Access Token Management ASP.NET Core - OAuth 2.0 Cl… ASP.NET Core - Using Mutliple Authentication Schemes ASP.NET Core - Using Mutlip… Serilog - Console Sink Themes Serilog - Console Sink Them… Azure DevOps Build - Could not locate the assembly Azure DevOps Build - Could … Docker - SQL Error on ASP.NET Core Alpine Docker - SQL Error on ASP.N… ASP.NET Core #aspnet-core API #api ASP.NET Core - Return 500 (Intern…

webmentions · 2 mentions

  • by Anderson Robin · Jun 26, 2022 · mention

    Are you looking for an answer to the topic “actionresult internal server error“? We answer all your questions at the website Brandiscrafts.com in category: Latest technology and computer news updates. You will find the answer right below. Keep Reading Actionresult Internal Server Error Table of Contents How do you handle internal server error? What is ActionResult in ASP.NET Core?Chữa lỗi HTTP

  • Someone · Dec 25, 2021 · mention

    The Internet facilitates people’s lives. You can do almost anything online: manage your bank deposits, buy food, order air tickets, and so on. This means that the account is important to you. Set strong and different passwords for each service. If you have many accounts, then here is a suggestion: make use of a password manager. 511 Network Authentication Required — httpstatuses.com https://htt

comments

loading discussion…