How can I set the reason phrase on a HTTP response in ASP.NET Core from some middleware?
In previous versions (full framework), I would do the following:
context.Response.StatusCode = 401;
context.Response.ReasonPhrase = "Missing or invalid token.";
In ASP.NET Core, the only property available is the StatusCode
.
Here is an example of a Fiddler capture with a custom reason set on the response.
In a browser with developer tools enabled, make a request to the sample app with the path /redirect-rule/1234/5678 . The regular expression matches the request path on redirect-rule/(. *) , and the path is replaced with /redirected/1234/5678 . The redirect URL is sent back to the client with a 302 - Found status code.
These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline.
Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.
Because there are multiple return types and paths in this type of action, liberal use of the [ProducesResponseType] attribute is necessary. This attribute produces more descriptive response details for web API help pages generated by tools like Swagger.
Try this:
context.Response.StatusCode = 401;
context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Missing or invalid token.";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With