Implementing Message Handlers in MVC 6

1.1k views Asked by At

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.

1

There are 1 answers

2
N. Taylor Mullen On

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();
            }
        });
    }
}