In previous article, we have seen three different ways to handle exceptions in .NET core web API applications.
When a new ASP .NET Core web API project is created, the default project template has a request processing pipeline already defined. In the default pipeline, generally there is a middleware for showing exception page. In this article, let’s understand details about this middleware.
What is it ?
The Developer Exception Page shows details about the exceptions, like stack trace, HTTP headers, cookies, query strings etc. which would be helpful for debugging.
This functionality can be achieved by adding a DeveloperExceptionPageMiddleware to the request processing pipeline. Default template has the middleware, and it is applied only on development
environment. General recommendation is to return exception details to callers only on dev environment.
This middleware should be registered as early as possible in the request processing pipeline- so that it can show details of exceptions from other middlewares which follow it.
e.g. if you register developer exception middleware after UseRouting, it would not be able to catch exceptions raised from UseRouting middleware.
Example
Below is a code for a sample .NET Core web API application. It shows a sample GetValueController
and startup.cs
. The controller’s method raises an exception if the incoming parameter from URL is null
or empty
.
When an ASP .NET Core web API project is created, swagger support is by default available for the app. So, when we run this project, it should show swagger page. Let’s not pass input parameter to see if swagger can show exception details.
When the input parameter is not sent in request, we can see stack trace and other details in swagger UI as shown in below snapshot. So, the stack trace and other exception details seems to be returned as a plain text
.
Response Type
So, as per documentation, if no request header is sent, Developer Exception Page middleware
sends that plain text
output. If the caller wants output in HTML format, the request header – accept
– should be sent with the request. And its value should be set to text/html
media type.
If we want to test this it can be easily tested. We already have seen that plain text
is returned via swagger call.
We can also check in postman. Create a GET
request for our API with Accept
header set to text/html
media type. It should return HTML response as shown below.
So, I hope you find this information useful. Let me know your thoughts.
Pingback: The Code Blogger - Request Processing Pipeline In .NET Core Web APIs