| title | author | description | monikerRange | ms.author | ms.custom | ms.date | uid |
|---|---|---|---|---|---|---|---|
|
Handle errors in ASP.NET Core web APIs |
tdykstra |
Learn about error handling with ASP.NET Core web APIs. |
>= aspnetcore-3.1 |
riande |
mvc |
10/14/2022 |
web-api/handle-errors |
Handle errors in ASP.NET Core web APIs
:::moniker range=»>= aspnetcore-7.0″
This article describes how to handle errors and customize error handling with ASP.NET Core web APIs.
Developer Exception Page
The Developer Exception Page shows detailed stack traces for server errors. It uses xref:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. For example, consider the following controller action, which throws an exception:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_Throw»:::
When the Developer Exception Page detects an unhandled exception, it generates a default plain-text response similar to the following example:
HTTP/1.1 500 Internal Server Error Content-Type: text/plain; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked System.Exception: Sample exception. at HandleErrorsSample.Controllers.ErrorsController.Get() in ... at lambda_method1(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync() ...
If the client requests an HTML-formatted response, the Developer Exception Page generates a response similar to the following example:
HTTP/1.1 500 Internal Server Error Content-Type: text/html; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Internal Server Error</title> <style> body { font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif; font-size: .813em; color: #222; background-color: #fff; } h1 { color: #44525e; margin: 15px 0 15px 0; } ...
To request an HTML-formatted response, set the Accept HTTP request header to text/html.
[!WARNING]
Don’t enable the Developer Exception Page unless the app is running in the Development environment. Don’t share detailed exception information publicly when the app runs in production. For more information on configuring environments, see xref:fundamentals/environments.
Exception handler
In non-development environments, use Exception Handling Middleware to produce an error payload:
-
In
Program.cs, call xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A to add the Exception Handling Middleware::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Program.cs» id=»snippet_Middleware» highlight=»7″:::
-
Configure a controller action to respond to the
/errorroute::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_HandleError»:::
The preceding HandleError action sends an RFC 7807-compliant payload to the client.
[!WARNING]
Don’t mark the error handler action method with HTTP method attributes, such asHttpGet. Explicit verbs prevent some requests from reaching the action method.For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its xref:Microsoft.AspNetCore.Mvc.ApiExplorerSettingsAttribute.IgnoreApi%2A property to
true. This attribute configuration excludes the error handler action from the app’s OpenAPI specification:[ApiExplorerSettings(IgnoreApi = true)]Allow anonymous access to the method if unauthenticated users should see the error.
Exception Handling Middleware can also be used in the Development environment to produce a consistent payload format across all environments:
-
In
Program.cs, register environment-specific Exception Handling Middleware instances::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConsistentEnvironments»:::
In the preceding code, the middleware is registered with:
- A route of
/error-developmentin the Development environment. - A route of
/errorin non-Development environments.
- A route of
-
Add controller actions for both the Development and non-Development routes:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_ConsistentEnvironments»:::
Use exceptions to modify the response
The contents of the response can be modified from outside of the controller using a custom exception and an action filter:
-
Create a well-known exception type named
HttpResponseException::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseException.cs» id=»snippet_Class»:::
-
Create an action filter named
HttpResponseExceptionFilter::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseExceptionFilter.cs» id=»snippet_Class»:::
The preceding filter specifies an
Orderof the maximum integer value minus 10. ThisOrderallows other filters to run at the end of the pipeline. -
In
Program.cs, add the action filter to the filters collection::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_AddHttpResponseExceptionFilter»:::
Validation failure error response
For web API controllers, MVC responds with a xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails response type when model validation fails. MVC uses the results of xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example replaces the default factory with an implementation that also supports formatting responses as XML, in Program.cs:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConfigureInvalidModelStateResponseFactory»:::
Client error response
An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to produce a xref:Microsoft.AspNetCore.Mvc.ProblemDetails.
The automatic creation of a ProblemDetails for error status codes is enabled by default, but error responses can be configured in one of the following ways:
- Use the problem details service
- Implement ProblemDetailsFactory
- Use ApiBehaviorOptions.ClientErrorMapping
Default problem details response
The following Program.cs file was generated by the web application templates for API controllers:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_default»:::
Consider the following controller, which returns xref:Microsoft.AspNetCore.Http.HttpResults.BadRequest when the input is invalid:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Controllers/ValuesController.cs» id=»snippet_1″:::
A problem details response is generated with the previous code when any of the following conditions apply:
- The
/api/values2/divideendpoint is called with a zero denominator. - The
/api/values2/squarerootendpoint is called with a radicand less than zero.
The default problem details response body has the following type, title, and status values:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "00-84c1fd4063c38d9f3900d06e56542d48-85d1d4-00"
}
Problem details service
ASP.NET Core supports creating Problem Details for HTTP APIs using the xref:Microsoft.AspNetCore.Http.IProblemDetailsService. For more information, see the Problem details service.
The following code configures the app to generate a problem details response for all HTTP client and server error responses that don’t have a body content yet:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_apishort» highlight=»4,8-9,13″:::
Consider the API controller from the previous section, which returns xref:Microsoft.AspNetCore.Http.HttpResults.BadRequest when the input is invalid:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Controllers/ValuesController.cs» id=»snippet_1″:::
A problem details response is generated with the previous code when any of the following conditions apply:
- An invalid input is supplied.
- The URI has no matching endpoint.
- An unhandled exception occurs.
The automatic creation of a ProblemDetails for error status codes is disabled when the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.SuppressMapClientErrors%2A property is set to true:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_disable» highlight=»4-7″:::
Using the preceding code, when an API controller returns BadRequest, an HTTP 400 response status is returned with no response body. SuppressMapClientErrors prevents a ProblemDetails response from being created, even when calling WriteAsync for an API Controller endpoint. WriteAsync is explained later in this article.
The next section shows how to customize the problem details response body, using xref:Microsoft.AspNetCore.Http.ProblemDetailsOptions.CustomizeProblemDetails, to return a more helpful response. For more customization options, see Customizing problem details.
Customize problem details with CustomizeProblemDetails
The following code uses xref:Microsoft.AspNetCore.Http.ProblemDetailsOptions to set xref:Microsoft.AspNetCore.Http.ProblemDetailsOptions.CustomizeProblemDetails:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_api_controller» highlight=»6″:::
The updated API controller:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Controllers/ValuesController.cs» id=»snippet» highlight=»9-17,27-35″:::
The following code contains the MathErrorFeature and MathErrorType, which are used with the preceding sample:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/MathErrorFeature.cs» :::
A problem details response is generated with the previous code when any of the following conditions apply:
- The
/divideendpoint is called with a zero denominator. - The
/squarerootendpoint is called with a radicand less than zero. - The URI has no matching endpoint.
The problem details response body contains the following when either squareroot endpoint is called with a radicand less than zero:
{
"type": "https://en.wikipedia.org/wiki/Square_root",
"title": "Bad Input",
"status": 400,
"detail": "Negative or complex numbers are not allowed."
}
View or download sample code
Implement ProblemDetailsFactory
MVC uses xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory?displayProperty=fullName to produce all instances of xref:Microsoft.AspNetCore.Mvc.ProblemDetails and xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails. This factory is used for:
- Client error responses
- Validation failure error responses
- xref:Microsoft.AspNetCore.Mvc.ControllerBase.Problem%2A?displayProperty=nameWithType and xref:Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem%2A?displayProperty=nameWithType
To customize the problem details response, register a custom implementation of xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory in Program.cs:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ReplaceProblemDetailsFactory»:::
Use ApiBehaviorOptions.ClientErrorMapping
Use the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.ClientErrorMapping%2A property to configure the contents of the ProblemDetails response. For example, the following code in Program.cs updates the xref:Microsoft.AspNetCore.Mvc.ClientErrorData.Link%2A property for 404 responses:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ClientErrorMapping»:::
Additional resources
- How to Use ModelState Validation in ASP.NET Core Web API
- View or download sample code
- Hellang.Middleware.ProblemDetails
:::moniker-end
:::moniker range=»= aspnetcore-6.0″
This article describes how to handle errors and customize error handling with ASP.NET Core web APIs.
Developer Exception Page
The Developer Exception Page shows detailed stack traces for server errors. It uses xref:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. For example, consider the following controller action, which throws an exception:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_Throw»:::
When the Developer Exception Page detects an unhandled exception, it generates a default plain-text response similar to the following example:
HTTP/1.1 500 Internal Server Error Content-Type: text/plain; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked System.Exception: Sample exception. at HandleErrorsSample.Controllers.ErrorsController.Get() in ... at lambda_method1(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync() ...
If the client requests an HTML-formatted response, the Developer Exception Page generates a response similar to the following example:
HTTP/1.1 500 Internal Server Error Content-Type: text/html; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Internal Server Error</title> <style> body { font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif; font-size: .813em; color: #222; background-color: #fff; } h1 { color: #44525e; margin: 15px 0 15px 0; } ...
To request an HTML-formatted response, set the Accept HTTP request header to text/html.
[!WARNING]
Don’t enable the Developer Exception Page unless the app is running in the Development environment. Don’t share detailed exception information publicly when the app runs in production. For more information on configuring environments, see xref:fundamentals/environments.
Exception handler
In non-development environments, use Exception Handling Middleware to produce an error payload:
-
In
Program.cs, call xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A to add the Exception Handling Middleware::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Program.cs» id=»snippet_Middleware» highlight=»7″:::
-
Configure a controller action to respond to the
/errorroute::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_HandleError»:::
The preceding HandleError action sends an RFC 7807-compliant payload to the client.
[!WARNING]
Don’t mark the error handler action method with HTTP method attributes, such asHttpGet. Explicit verbs prevent some requests from reaching the action method.For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its xref:Microsoft.AspNetCore.Mvc.ApiExplorerSettingsAttribute.IgnoreApi%2A property to
true. This attribute configuration excludes the error handler action from the app’s OpenAPI specification:[ApiExplorerSettings(IgnoreApi = true)]Allow anonymous access to the method if unauthenticated users should see the error.
Exception Handling Middleware can also be used in the Development environment to produce a consistent payload format across all environments:
-
In
Program.cs, register environment-specific Exception Handling Middleware instances::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConsistentEnvironments»:::
In the preceding code, the middleware is registered with:
- A route of
/error-developmentin the Development environment. - A route of
/errorin non-Development environments.
- A route of
-
Add controller actions for both the Development and non-Development routes:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_ConsistentEnvironments»:::
Use exceptions to modify the response
The contents of the response can be modified from outside of the controller using a custom exception and an action filter:
-
Create a well-known exception type named
HttpResponseException::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseException.cs» id=»snippet_Class»:::
-
Create an action filter named
HttpResponseExceptionFilter::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseExceptionFilter.cs» id=»snippet_Class»:::
The preceding filter specifies an
Orderof the maximum integer value minus 10. ThisOrderallows other filters to run at the end of the pipeline. -
In
Program.cs, add the action filter to the filters collection::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_AddHttpResponseExceptionFilter»:::
Validation failure error response
For web API controllers, MVC responds with a xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails response type when model validation fails. MVC uses the results of xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example replaces the default factory with an implementation that also supports formatting responses as XML, in Program.cs:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConfigureInvalidModelStateResponseFactory»:::
Client error response
An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to produce a xref:Microsoft.AspNetCore.Mvc.ProblemDetails.
The error response can be configured in one of the following ways:
- Implement ProblemDetailsFactory
- Use ApiBehaviorOptions.ClientErrorMapping
Implement ProblemDetailsFactory
MVC uses xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory?displayProperty=fullName to produce all instances of xref:Microsoft.AspNetCore.Mvc.ProblemDetails and xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails. This factory is used for:
- Client error responses
- Validation failure error responses
- xref:Microsoft.AspNetCore.Mvc.ControllerBase.Problem%2A?displayProperty=nameWithType and xref:Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem%2A?displayProperty=nameWithType
To customize the problem details response, register a custom implementation of xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory in Program.cs:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ReplaceProblemDetailsFactory»:::
Use ApiBehaviorOptions.ClientErrorMapping
Use the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.ClientErrorMapping%2A property to configure the contents of the ProblemDetails response. For example, the following code in Program.cs updates the xref:Microsoft.AspNetCore.Mvc.ClientErrorData.Link%2A property for 404 responses:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ClientErrorMapping»:::
Custom Middleware to handle exceptions
The defaults in the exception handling middleware work well for most apps. For apps that require specialized exception handling, consider customizing the exception handling middleware.
Produce a ProblemDetails payload for exceptions
ASP.NET Core doesn’t produce a standardized error payload when an unhandled exception occurs. For scenarios where it’s desirable to return a standardized ProblemDetails response to the client, the ProblemDetails middleware can be used to map exceptions and 404 responses to a ProblemDetails payload. The exception handling middleware can also be used to return a xref:Microsoft.AspNetCore.Mvc.ProblemDetails payload for unhandled exceptions.
Additional resources
- How to Use ModelState Validation in ASP.NET Core Web API
- View or download sample code (How to download)
:::moniker-end
:::moniker range=»< aspnetcore-6.0″
This article describes how to handle and customize error handling with ASP.NET Core web APIs.
View or download sample code (How to download)
Developer Exception Page
The Developer Exception Page is a useful tool to get detailed stack traces for server errors. It uses xref:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. To illustrate, consider the following controller action:
:::code language=»csharp» source=»handle-errors/samples/3.x/Controllers/WeatherForecastController.cs» id=»snippet_GetByCity»:::
Run the following curl command to test the preceding action:
curl -i https://localhost:5001/weatherforecast/chicago
The Developer Exception Page displays a plain-text response if the client doesn’t request HTML-formatted output. The following output appears:
HTTP/1.1 500 Internal Server Error Transfer-Encoding: chunked Content-Type: text/plain Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET Date: Fri, 27 Sep 2019 16:13:16 GMT System.ArgumentException: We don't offer a weather forecast for chicago. (Parameter 'city') at WebApiSample.Controllers.WeatherForecastController.Get(String city) in C:working_folderaspnetAspNetCore.Docsaspnetcoreweb-apihandle-errorssamples3.xControllersWeatherForecastController.cs:line 34 at lambda_method(Closure , Object , Object[] ) at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) HEADERS ======= Accept: */* Host: localhost:44312 User-Agent: curl/7.55.1
To display an HTML-formatted response instead, set the Accept HTTP request header to the text/html media type. For example:
curl -i -H "Accept: text/html" https://localhost:5001/weatherforecast/chicago
Consider the following excerpt from the HTTP response:
HTTP/1.1 500 Internal Server Error Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET Date: Fri, 27 Sep 2019 16:55:37 GMT <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Internal Server Error</title> <style> body { font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif; font-size: .813em; color: #222; background-color: #fff; }
The HTML-formatted response becomes useful when testing via tools like Postman. The following screen capture shows both the plain-text and the HTML-formatted responses in Postman:
:::image source=»handle-errors/_static/developer-exception-page-postman.gif» alt-text=»Test the Developer Exception Page in Postman.»:::
[!WARNING]
Enable the Developer Exception Page only when the app is running in the Development environment. Don’t share detailed exception information publicly when the app runs in production. For more information on configuring environments, see xref:fundamentals/environments.Don’t mark the error handler action method with HTTP method attributes, such as
HttpGet. Explicit verbs prevent some requests from reaching the action method. Allow anonymous access to the method if unauthenticated users should see the error.
Exception handler
In non-development environments, Exception Handling Middleware can be used to produce an error payload:
-
In
Startup.Configure, invoke xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A to use the middleware::::code language=»csharp» source=»handle-errors/samples/3.x/Startup.cs» id=»snippet_UseExceptionHandler» highlight=»9″:::
-
Configure a controller action to respond to the
/errorroute::::code language=»csharp» source=»handle-errors/samples/3.x/Controllers/ErrorController.cs» id=»snippet_ErrorController»:::
The preceding Error action sends an RFC 7807-compliant payload to the client.
Exception Handling Middleware can also provide more detailed content-negotiated output in the local development environment. Use the following steps to produce a consistent payload format across development and production environments:
-
In
Startup.Configure, register environment-specific Exception Handling Middleware instances:public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseExceptionHandler("/error-local-development"); } else { app.UseExceptionHandler("/error"); } }
In the preceding code, the middleware is registered with:
- A route of
/error-local-developmentin the Development environment. - A route of
/errorin environments that aren’t Development.
- A route of
-
Apply attribute routing to controller actions:
:::code language=»csharp» source=»handle-errors/samples/3.x/Controllers/ErrorController.cs» id=»snippet_ErrorControllerEnvironmentSpecific»:::
The preceding code calls ControllerBase.Problem to create a xref:Microsoft.AspNetCore.Mvc.ProblemDetails response.
Use exceptions to modify the response
The contents of the response can be modified from outside of the controller. In ASP.NET 4.x Web API, one way to do this was using the xref:System.Web.Http.HttpResponseException type. ASP.NET Core doesn’t include an equivalent type. Support for HttpResponseException can be added with the following steps:
-
Create a well-known exception type named
HttpResponseException::::code language=»csharp» source=»handle-errors/samples/3.x/Exceptions/HttpResponseException.cs» id=»snippet_HttpResponseException»:::
-
Create an action filter named
HttpResponseExceptionFilter::::code language=»csharp» source=»handle-errors/samples/3.x/Filters/HttpResponseExceptionFilter.cs» id=»snippet_HttpResponseExceptionFilter»:::
The preceding filter specifies an
Orderof the maximum integer value minus 10. ThisOrderallows other filters to run at the end of the pipeline. -
In
Startup.ConfigureServices, add the action filter to the filters collection::::code language=»csharp» source=»handle-errors/samples/3.x/Startup.cs» id=»snippet_AddExceptionFilter»:::
Validation failure error response
For web API controllers, MVC responds with a xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails response type when model validation fails. MVC uses the results of xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example uses the factory to change the default response type to xref:Microsoft.AspNetCore.Mvc.SerializableError in Startup.ConfigureServices:
:::code language=»csharp» source=»handle-errors/samples/3.x/Startup.cs» id=»snippet_DisableProblemDetailsInvalidModelStateResponseFactory» highlight=»4-13″:::
Client error response
An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to a result with xref:Microsoft.AspNetCore.Mvc.ProblemDetails.
The error response can be configured in one of the following ways:
- Implement ProblemDetailsFactory
- Use ApiBehaviorOptions.ClientErrorMapping
Implement ProblemDetailsFactory
MVC uses xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory?displayProperty=fullName to produce all instances of xref:Microsoft.AspNetCore.Mvc.ProblemDetails and xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails. This factory is used for:
- Client error responses
- Validation failure error responses
- xref:Microsoft.AspNetCore.Mvc.ControllerBase.Problem%2A?displayProperty=nameWithType and xref:Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem%2A?displayProperty=nameWithType >
To customize the problem details response, register a custom implementation of xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory in Startup.ConfigureServices:
public void ConfigureServices(IServiceCollection serviceCollection) { services.AddControllers(); services.AddTransient<ProblemDetailsFactory, CustomProblemDetailsFactory>(); }
Use ApiBehaviorOptions.ClientErrorMapping
Use the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.ClientErrorMapping%2A property to configure the contents of the ProblemDetails response. For example, the following code in Startup.ConfigureServices updates the type property for 404 responses:
:::code language=»csharp» source=»index/samples/3.x/Startup.cs» id=»snippet_ConfigureApiBehaviorOptions» highlight=»8-9″:::
Custom Middleware to handle exceptions
The defaults in the exception handling middleware work well for most apps. For apps that require specialized exception handling, consider customizing the exception handling middleware.
Producing a ProblemDetails payload for exceptions
ASP.NET Core doesn’t produce a standardized error payload when an unhandled exception occurs. For scenarios where it’s desirable to return a standardized ProblemDetails response to the client, the ProblemDetails middleware can be used to map exceptions and 404 responses to a ProblemDetails payload. The exception handling middleware can also be used to return a xref:Microsoft.AspNetCore.Mvc.ProblemDetails payload for unhandled exceptions.
:::moniker-end

In this article, we will see how to return HTTP Status codes in .NET Core methods based on the HTTP Operation in API.
We shall also see the most commonly asked format like returning HTTP Status code 500 Internal server error etc.
We will cover the below aspects in today’s article,
- Built-in HTTPS Status Code for .NET Core
- HTTP Status Code – 200 (OK)
- What is HTTP Status Ok or 200?
- HTTP Status Code – 400 (Bad Request)
- HTTP Status Code – 500 (InternalServerError )
- Return HTTP 500 using the Status code
- Using ProblemDetails and Best practices
- Unhandled exception in API Pipeline?
- Summary
Example: One may return Web API with ASP.NET Core MVC 200, 500, or 503 error codes
RESTFul services principle talks about HTTP Status code and their usage.
It’s important to follow these REST HTTP Status codes appropriately when following REST specifications.
.NET Core has inbuilt support for all basic HTTP Status codes and they are easy to configure for almost all standard HTTP status codes.
RFC7231 defines the specification for this HTTP Status code in detail.
References:
- https://tools.ietf.org/html/rfc7231#section-6.5.1
RFC7807 defines the specification for error response for HTTP error operation
References:
- RFC7807 Problem Details HTTP error – Guidelines and Best practices
Built-in HTTPS Status Code for .NET Core
Please note that ASP.NET core provides built-in support for both RFC7231 and RFC7807, giving you direct capability on returning the standards HTTP status code plus additional details in case of error operations based on RFC specifications.
HTTP Status Code – 200 (OK)
If your controller method returns IActionResult,
What is HTTP Status Ok or 200?
- The HTTP 200 (OK) status code indicates success.
- This response also meant the response has the payload.
- If no payload is desired, the server should send a 204 (NoContent) status code.
One can use the built-in type Ok() as below,
[HttpGet]
public IActionResult GetSynchrounous(string id)
{
Book book = null;
//run method - Synchronously
book = _bookService.Get(id);
return Ok(book);
}
This built-in type does support sending additional details with its overloaded API.
Please do leverage those when required.

HTTP Status Code – 400 (Bad Request)
This status code means the server cannot process the request due to malformed requests, invalid requests, etc.
One can use the built-in type BadRequest() as below,
Example:
[HttpGet("book/{id}")]
public IActionResult GetAccount(string id)
{
if (id == null)
{
return BadRequest();
}
return Ok();
}
Below is the response for the above request (Using Chrome) will produce Status Code: 400 Bad Request,
Request URL: http://localhost:60213/api/books/book/1 Request Method: GET Status Code: 400 Bad Request Remote Address: [::1]:60213 Referrer Policy: no-referrer-when-downgrade
This built-in type does support sending additional details with its overloaded API.
The below response is based on RFC7807 which is a specification around how to use ProblemDetails.

Note: Controller method returning IActionResult has built-in supported Error response based on the RFC7807 Porblem details specifications.
HTTP Status Code – 500 (InternalServerError )
This status code means the server encountered an unexpected condition that prevented it from fulfilling the input request.
- Use built-in type StatusCode()
- Use Problem() or ProblemDetails() as per RFC7807
Return HTTP 500 using the Status code
Return HTTP 500 using the Status code below,
public IActionResult GetAccount1(string id)
{
Book book = null;
try
{
//run method - Synchronously
book = _bookService.Get(id);
if (book == null)
{
return NotFound();
}
book.Price = 10;
}
catch (Exception ex)
{
return StatusCode(500, "Internal Server Error. Something went Wrong!");
}
return Ok(book);
Using ProblemDetails and Best practices
You can return the HTTP status code using ProblemDetails. Kindly visit the below guidelines for more details,
- Using ProblemDetails in ASP.NET Core – Guidelines
Return HTTP 500 using ProblemDetails,
catch (Exception ex)
{
return Problem("Internal Server Error.Something went Wrong!");
}
Below is the response for the above request (Using Chrome) which produces Status Code: 500 Internal Server Error

Client-side,
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.6.1",
"title": "An error occured while processing your request.",
"status": 500,
"detail": "Internal Server Error.Something went Wrong!",
"traceId": "|5b367172-44fadfb7f6df04a9."
}
This built-in type does support sending additional details with its overloaded API.
- StatusCode( int statusCode, object value);
- StatusCode( int statusCode);
![]()
StatusCode can be used as an alternative for all other HTTP status codes where the built-in type is missing.
StatusCode class caN be used for all below-supported codes,
public static class StatusCodes
{
public const int Status100Continue = 100;
public const int Status412PreconditionFailed = 412;
public const int Status413PayloadTooLarge = 413;
public const int Status413RequestEntityTooLarge = 413;
public const int Status414RequestUriTooLong = 414;
public const int Status414UriTooLong = 414;
public const int Status415UnsupportedMediaType = 415;
public const int Status416RangeNotSatisfiable = 416;
public const int Status416RequestedRangeNotSatisfiable = 416;
public const int Status417ExpectationFailed = 417;
public const int Status418ImATeapot = 418;
public const int Status419AuthenticationTimeout = 419;
public const int Status421MisdirectedRequest = 421;
public const int Status422UnprocessableEntity = 422;
public const int Status423Locked = 423;
public const int Status424FailedDependency = 424;
public const int Status426UpgradeRequired = 426;
public const int Status428PreconditionRequired = 428;
public const int Status429TooManyRequests = 429;
public const int Status431RequestHeaderFieldsTooLarge = 431;
public const int Status451UnavailableForLegalReasons = 451;
public const int Status500InternalServerError = 500;
public const int Status501NotImplemented = 501;
public const int Status502BadGateway = 502;
public const int Status503ServiceUnavailable = 503;
public const int Status504GatewayTimeout = 504;
public const int Status505HttpVersionNotsupported = 505;
public const int Status506VariantAlsoNegotiates = 506;
public const int Status507InsufficientStorage = 507;
public const int Status508LoopDetected = 508;
public const int Status411LengthRequired = 411;
public const int Status510NotExtended = 510;
public const int Status410Gone = 410;
public const int Status408RequestTimeout = 408;
public const int Status101SwitchingProtocols = 101;
public const int Status102Processing = 102;
public const int Status200OK = 200;
public const int Status201Created = 201;
public const int Status202Accepted = 202;
public const int Status203NonAuthoritative = 203;
public const int Status204NoContent = 204;
public const int Status205ResetContent = 205;
public const int Status206PartialContent = 206;
public const int Status207MultiStatus = 207;
public const int Status208AlreadyReported = 208;
public const int Status226IMUsed = 226;
public const int Status300MultipleChoices = 300;
public const int Status301MovedPermanently = 301;
public const int Status302Found = 302;
public const int Status303SeeOther = 303;
public const int Status304NotModified = 304;
public const int Status305UseProxy = 305;
public const int Status306SwitchProxy = 306;
public const int Status307TemporaryRedirect = 307;
public const int Status308PermanentRedirect = 308;
public const int Status400BadRequest = 400;
public const int Status401Unauthorized = 401;
public const int Status402PaymentRequired = 402;
public const int Status403Forbidden = 403;
public const int Status404NotFound = 404;
public const int Status405MethodNotAllowed = 405;
public const int Status406NotAcceptable = 406;
public const int Status407ProxyAuthenticationRequired = 407;
public const int Status409Conflict = 409;
public const int Status511NetworkAuthenticationRequired = 511;
}
Unhandled exception in API Pipeline?
It’s recommended to use the Global exception middleware or handler approach for any unhandled exception in the API pipeline.
Users should vary on what exception should reach the consumer as a business exception Vs what can be logged in the form of technical server logging.
Kindly see below the reference article on best practices of exception handling,
- Best Practices for Exception Handling in .NET Core
- RFC7807 Problem Details HTTP error – Guidelines and Best practices
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
References :
- API Versioning Best practices in ASP.NET Core with Examples
- Global Exception Handling in ASP.NET Core using Middleware component
Summary
It’s important to follow HTTP Status codes appropriately when following REST specifications for any communication between the client and servicer.
Today we learned that .NET Core has provided support for using almost all HTTP status codes allowing us to follow specifications and principles around the same based on standards RFC guidelines.
References:
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published best practices and guidelines for software design and development.
Отправка статусных кодов
Последнее обновление: 21.03.2022
Нередко возникает необходимость отправить в ответ на запрос какой-либо статусный код.
Например, если пользователь пытается получить доступ к ресурсу, который недоступен, или для которого у пользователя нету прав. Либо если просто нужно
уведомить браузер пользователя с помощью статусного кода об успешном выполнении операции, как иногда применяется в ajax-запросах. Для этого в ASP.NET Core MVC
определена богатая палитра классов, которые можно использовать для отправки статусного кода.
StatusCodeResult
StatusCodeResult позволяет отправить любой статусный код клиенту:
public IActionResult Index()
{
return StatusCode(401);
}
Для создания этого результата используется метод StatusCode(), в который передается отправляемый код статуса.
Подобным образом мы можем послать браузеру любой другой статусный код. Но для отдельных кодов статуса предназначены свои отдельные классы.
HttpNotFoundResult и HttpNotFoundObjectResult
NotFoundResult и NotFoundObjectResult посылает код 404, уведомляя браузер о том, что ресурс
не найден. Второй класс в дополнении к статусному коду позволяет отправить доплнительную информацию, которая потом отобразится в браузере.
Объекты обоих классов создаются методом NotFound. Для первого класса — это метод без параметров, для второго класса — метод,
который в качестве параметра принимает отправляемую информацию. Например, используем NotFoundObjectResult:
public IActionResult Index()
{
return NotFound("Resource not found");
}

UnauthorizedResult и UnauthorizedObjectResult
UnauthorizedResult посылает код 401, уведомляя пользователя, что он не автризован для доступа к ресурсу:
public IActionResult Index(int age)
{
if (age < 18) return Unauthorized();
return Content("Access is available");
}
Для создания ответа используется метод Unauthorized().
UnauthorizedObjectResult также посылает код 401, только позволяет добавить в ответ некоторый объект с информацией об ошибке:
public class HomeController : Controller
{
public IActionResult Index(int age)
{
if (age < 18) return Unauthorized(new Error("Access is denied"));
return Content("Access is available");
}
}
record class Error(string Message);

BadResult и BadObjectResult
BadResult и BadObjectResult посылают код 400, что говорит о том, что запрос некорректный.
Второй класс в дополнении к статусному коду позволяет отправить доплнительную информацию, которая потом отобразится в браузере.
Эти классы можно применять, например, если в запросе нет каких-то параметров или данные представляют совсем не те типы, которые мы ожидаем получить, и т.д.
Объекты обоих классов создаются методом BadRequest. Для первого класса — это метод без параметров, для второго класса — метод,
который в качестве параметра принимает отправляемую информацию:
public IActionResult Index(string? name)
{
if (string.IsNullOrEmpty(name)) return BadRequest("Name undefined");
return Content($"Name: {name}");
}
OkResult и OkObjectResult
OkResult и OkObjectResult посылают код 200, уведомляя об успешном выполнении запроса.
Второй класс в дополнении к статусному коду позволяет отправить дополнительную информацию, которая потом отправляется клиенту в формате json.
Объекты обоих классов создаются методом Ok(). Для первого класса — это метод без параметров, для второго класса — метод,
который в качестве параметра принимает отправляемую информацию:
public IActionResult Index()
{
return Ok("Don't worry. Be happy");
}
Back to: ASP.NET Core Web API Tutorials
In this article, I am going to discuss HTTP Status Code in ASP.NET Core Web API. Returning the response with a proper status code is the backbone of any restful Web APIs. Now, it is time to learn how can we format the response with the proper response code as per our business requirement.
HTTP Status Codes:
The HyperText Transport Protocol status code is one of the important components of HTTP Response. The Status code is issued from the server and they give information about the response. Whenever we get any response from the server, in that Response, we must have one HTTP Status code. All the HTTP Status codes are divided into five categories. They are as follows. Here, XX will represent the actual number.
- 1XX: Informational Response (Example: 100, 101, 102, etc.)
- 2XX: Successful, whenever you get 2XX as the response code, it means the request is successful. For example, we get 200 HTTP Status Code for the success of a GET request, 201 if a new resource has been successfully created. 204 status code is also for success but in return, it does not return anything just like if the client has performed a delete operation and in return doesn’t really expect something back.
- 3XX: 3XX HTTP status codes are basically used for redirection. Whenever you get 3XX as the response code, it means it is re-directional. for example, to tell a client that the requested resource like page, the image has been moved to another location.
- 4XX: 4XX HTTP status codes are meant to state errors or Client Error. Whenever you get 4XX as the response code, it means there is some problem with your request. For example, status code 400 means Bad Request, 401 is Unauthorized that is invalid authentication credentials or details have been provided by the client, 403 HTTP Status code means that authentication is a success, but the user is not authorized. 404 HTTP Status code means the requested resource is not available.
- 5XX: 5XX HTTP status codes are meant for Server Error. Whenever you get 5XX as the response code, it means there is some problem in the server. Internal Server Error exception is very common, which contains code 500. This error means that there is some unexpected error on the server and the client cannot do anything about it.
Frequently used HTTP Status Codes in ASP.NET Core Web API:
The following are some of the frequently used Status codes.
- 100: 100 means Continue. The HTTP 100 Continue informational status response code indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.
- 200: 200 means OK. The HTTP 200 OK success status response code indicates that the request has succeeded. If you are searching for some data and you got the data properly. That means the request is successful and, in that case, you will get 200 OK as the HTTP status code.
- 201: 201 means a new resource created. The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource. The new resource is effectively created before this response is sent back and the new resource is returned in the body of the message, its location being either the URL of the request or the content of the Location header. If you are adding successfully a new resource by using the HTTP Post method, then in that case you will get 201 as the Status code.
- 204: 204 means No Content. The HTTP 204 No Content success status response code indicates that a request has succeeded, but that the client doesn’t need to navigate away from its current page. If the server processed the request successfully and it is not returning any content, then in that case you will get a 204-response status code.
- 301: 301 means Moved Permanently. If you are getting 301 as a status code from the server, it means the resource you are looking for is moved permanently to the URL given by the Location headers.
- 302: 302 means Found. If you are getting 302 as a status code from the server, it means the resource you are looking for is moved temporarily to the URL given by the Location headers.
- 400: 400 means Bad Request. If you are getting 400 as the status code from the server, then the issue is with the client request. If the request contains some wrong data such as malformed request syntax, invalid request message framing, or deceptive request routing, then we will get this 400 Bad Request status code.
- 401: 401 means Unauthorized. If you are trying to access the resource for which you don’t have access (Invalid authentication credentials), then you will get a 401 unauthorized status code from the server.
- 404: 404 means Not Found. If you are looking for a resource that does not exist, then you will get this 404 Not Found status code from the server. Links that lead to a 404 page are often called broken or dead links.
- 405: 405 means Method Not Allowed. The 405 Method Not Allowed response status code indicates that the request method is known by the server but is not supported by the target resource. For example, we have one method which is a POST method in the server and we trying to access that method from the client using GET Verb, then, in that case, you will get a 405-status code.
- 500: 500 means Internal Server Error. If there is some error in the server, then you will get a 500 Internal Server Error status code.
- 503: 503 means Service Unavailable. The 503 Service Unavailable server error response code indicates that the server is not ready to handle the request. If the server is down for maintenance or the server is overloaded then in that case, you will get the 503 Service Unavailable Status code.
- 504: 504 means Gateway Timeout. The 504 Gateway Timeout server error response code indicates that the server while acting as a gateway or proxy, did not get a response in time from the upstream server that is needed in order to complete the request.
Why HTTP Status Codes are Important?
If we want to consume any Restful API, then we will send an HTTP Request and in return, we will get the response and the response include data as well as an HTTP Status code. The HTTP Status codes are important because they tell the client (client means who initiate the request, for example, Web, Android, iOS, Postman, IoT, Fiddler, etc) about what exactly happened to the request. If you send a wrong HTTP Status code, then that will confuse the client i.e. the consumer of the API.
The client should know that its request has been taken care of or not, and if the response is not as expected, then the Status Code should tell the client where the problem is? Whether the problem is at the Client level or at the API level.
Suppose there is a situation where the client gets the response with the HTTP status code as 200, but at the API level, there is some problem or issue. In that case, as the client gets 200 HTTP Status code, so the client will get a false assumption of everything being fine, whereas that won’t be the case.
So, if there is something wrong at the API level or there are some errors that occurred on the server, the HTTP status code 500 should be sent to the client so that the client knows there is something wrong with the request being sent. This is the reason why sending proper HTTP Response code from Restful APIs is important.
In our next article, we will discuss how to return 200 HTTP Status Codes in ASP.NET Core Web API. Here, in this article, I try to give an overview of HTTP Status Code in ASP.NET Core Web API.
Request and response are the backbones of any RESTful Web API. Every status code has a specific meaning and during the development, we must make sure that we are returning a valid response with a valid status code.
What is the Status Code
Status code is a numeric value, and it is the main component of HTTP Response. The status code is issued by the server based on the operation, input data, and some other parameters.
The status code gives some useful information about the behavior of the response.
Status code categories
All status codes are divided into the following 5 categories,
- 1xx – Informational
- 2xx – Successful
- 3xx – Redirection
- 4xx – Client Error
- 5xx – Server Error
Asp.Net Core Web API has some built-in methods to return the proper status code.
Setup the project
Let us create a new Asp.Net Core Web API application. Now in this application let’s add a new class Employee.cs under the Model folder.
- public class Employee
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string Email { get; set; }
- }
We also need to add a new controller with name EmployeesController at the Controllers folder.
- [Route(«api/[controller]»)]
- [ApiController]
- public class EmployeesController : ControllerBase
- {
- }
Time to create some hard-coded, in-memory data for employees. because we are only learning about the status code and how to return them from asp.net core web api so hard code data will work for the demo app. In a real application, you will get the data from a database.
For this, we will create a new private method in the EmployeesController.
- private List<Employee> EmployeeData()
- {
- return new List<Employee>()
- {
- new Employee(){ Id=1, Name = «Employee 1», Email = «employee1@nitishkaushik.com»},
- new Employee(){ Id=2, Name = «Employee 2», Email = «employee2@nitishkaushik.com»},
- new Employee(){ Id=3, Name = «Employee 3», Email = «employee3@nitishkaushik.com»},
- new Employee(){ Id=4, Name = «Employee 4», Email = «employee4@nitishkaushik.com»},
- new Employee(){ Id=5, Name = «Employee 5», Email = «employee5@nitishkaushik.com»}
- };
- }
Let us learn about the status code and how to return them from Asp.Net Core Web API,
200 status code
This is the most common status code that is returned from Web API.
This 200 status code belongs to the Successful category. It means everything about the operation is successful.
Example
- Get all employees data
- Get single employee data
Asp.Net Core has Ok() method to return 200 status code.
- public IActionResult GetEmployees()
- {
- return Ok();
- }
This Ok() method can have none or object parameters.
- public IActionResult GetEmployees()
- {
- var employees = EmployeeData();
- return Ok(employees);
- }
201 Status code
201 status code indicates that the new resource has been created successfully and the server will return the link to get that newly created resource.
In Asp.Net Core we can use the following methods to return the 201 status code.
- Created
- CreatedAtAction
- CreatedAtRoute
All these methods need the URL to get the newly created resource.
Created
- [HttpPost(«»)]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
- return Created(«~api/employees/1», model);
- }
CreatedAtAction
- [HttpGet(«{id}»)]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- var employee = EmployeeData().Where(x => x.Id == id).FirstOrDefault();
- return Ok(employee);
- }
- [HttpPost(«»)]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
- int newEmployeeId = 1;
- return CreatedAtAction(«GetEmployeeById», new { id = newEmployeeId }, model);
- }
CreatedAtRoute
- [HttpGet]
- [Route(«{id}», Name = «getEmployeeRoute»)]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- var employee = EmployeeData().Where(x => x.Id == id).FirstOrDefault();
- return Ok(employee);
- }
- [HttpPost(«»)]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
- int newEmployeeId = 1;
- return CreatedAtRoute(«getEmployeeRoute», new { id = newEmployeeId }, model);
- }
This method will add a new response header with a key Location and a URL in the value to get this resource.
202 status code
202 status indicates that the request has been accepted but the processing is not yet complete.
In Asp.Net Core we can use the following methods to return the 202 status code.
- Accepted
- AcceptedAtAction
- AcceptedAtRoute
- [HttpPost(«»)]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
- return Accepted();
- }
400 status code
400 status code indicated the bad request. It means there is something wrong in the request data.
In asp.net core we can return 400 status using the BadRequest method.
- [HttpPost(«»)]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
- return BadRequest();
- }
404 status code
If we are looking for a resource that does not exist, then the server returns a 404 status code.
In asp.net core we can return 404 status using the NotFound() method.
- [HttpGet]
- [Route(«{id}», Name = «getEmployeeRoute»)]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- var employee = EmployeeData().Where(x => x.Id == id).FirstOrDefault();
- if (employee == null)
- {
- return NotFound();
- }
- return Ok(employee);
- }
301 & 302 Status code
301 & 302 are used for local redirection. It means if you are trying to access an action method and from that action method you are redirecting the call to some other action method within the same application then in the response of this request there will be a 301 or 302 status code and a new response header with name Location.
The client will send another request on the value given in the Location header.
In case you are redirecting temporary then the status code will be 302. Or if you are redirecting permanently then the status code will be 301.
In asp.net core we can return 302 status using the LocalRedirect() method.
- [HttpGet]
- [Route(«{id}», Name = «getEmployeeRoute»)]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- return LocalRedirect(«~/api/employees»);
- }
In asp.net core we can return 302 status using the LocalRedirectPermanent() method.
- [HttpGet]
- [Route(«{id}», Name = «getEmployeeRoute»)]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- return LocalRedirectPermanent(«~/api/employees»);
- }
Other than this there are lots more built-in methods to return different status codes.
Click below to learn more about Asp.Net Core Web API,
- Asp.Net Core Web API Complete, Free and Step by Step Tutorial
