1

I have current API (web api 2) project that has a number of message handlers in use, some run for every request (checking to make sure the request is https and the request is coming from an authorised client) and some that run on specific routes (checking for the existence of a security token).

Now my question is how do I replicate this functionality in MVC 6, my current understanding is that it should be done through the use of middleware but I've not found an example that allows me to inspect the headers of the incoming request and should they not be what they are supposed to be return the appropriate http response code.

Gaz
  • 1,249
  • 3
  • 19
  • 37

1 Answers1

2

Middleware is definitely the right option to solve what you're looking to solve. I wrote a decent explanation about using/writing middlware here: ASP.NET MVC 6 handling errors based on HTTP status code

To specifically answer how to inspect headers here's an example:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
            if (!string.Equals(context.Request.Headers["myheader"], "somevalue", StringComparison.Ordinal))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Invalid headers");
            }
            else
            {
                await next();
            }
        });
    }
}
Community
  • 1
  • 1
N. Taylor Mullen
  • 18,061
  • 6
  • 49
  • 72
  • Trying to modify the status code or the headers after writing to the response stream will likely crash on streamed hosts like WebListener. You should set the status before calling `Write`/`WriteAsync`. You can also opt for buffering and replace the response stream by a `MemoryStream` that you would flush to the real stream at the end of your middleware. – Kévin Chalet Jun 27 '15 at 20:51
  • Is there a way of specifying a status msg as well as a code? Also do you know how I'd go about redirecting to a different route? – Gaz Jun 27 '15 at 22:25