Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the reason on a HttpResponse in ASP.NET Core from middlware

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.

Example of a reason sent from ASP.NET WebAPI (full framework)

like image 784
Kieron Avatar asked Feb 04 '17 10:02

Kieron


People also ask

How do I redirect in middleware NET Core?

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.

What happens when a terminal middleware is used in the request pipeline?

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.

What is the purpose middleware in ASP.NET Core?

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.

Is ProducesResponseType needed?

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.


1 Answers

Try this:

context.Response.StatusCode = 401;
context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Missing or invalid token.";
like image 183
Darin Dimitrov Avatar answered Sep 29 '22 17:09

Darin Dimitrov