Introduction
The process of choosing the best resource for a response when there are several resource representations available is known as content negotiation. Although content negotiation has been a feature of HTTP for some time, it may not be used as much as it could be for various reasons.
To put it briefly, content negotiation allows you to select, or more accurately, "negotiate," the content that is returned in response to a REST API request.
Customize 406 Status Code
When the Accept header in an ASP.NET Core Web API specifies a format that the server does not support, customizing the HTTP Response Body for a 406 Not Acceptable status code requires intercepting the content negotiation process or managing the result of a failed content negotiation. When content negotiation fails, this can be accomplished by using a custom middleware component to intercept and alter responses.
Create a Custom Middleware Component
A custom middleware that verifies outgoing responses can be made. You can alter the response appropriately in the event that a request is marked as 406 Not Acceptable due to a failure in content negotiation. So, copy and paste the following code into a class file called CustomNotAcceptableMiddleware.cs:
public class CustomNotAcceptableMiddleware(RequestDelegate next)
{
private readonly RequestDelegate _next = next;
public async Task Invoke(HttpContext context)
{
await _next(context);
if (context.Response.StatusCode == StatusCodes.Status406NotAcceptable)
{
// Bring the Accept header from the request
var acceptHeader = context.Request.Headers.Accept.ToString();
// Custom response logic here
context.Response.ContentType = "application/json";
var response = new
{
Code = StatusCodes.Status406NotAcceptable,
ErrorMessage = $"Please double check the provided requested format {acceptHeader} is not accepted."
};
await context.Response.WriteAsync(JsonSerializer.Serialize(response));
}
}
}
Configure the Middleware
Once your middleware has been created, register it in the request processing pipeline of the application. The Program.cs class file handles this. Thus, include the subsequent clause:
app.UseMiddleware<CustomNotAcceptableMiddleware>();
After making the aforementioned modifications, you will now receive the Custom Error Message and the 406 Not Acceptable Status Code when you attempt to send an HTTP Request with the Accept header value set to application/CSS, as seen in the following image.
We learned the new technique and evolved together.
Happy coding!