8

What's the difference between using a MessageHandler vs a Filter to check for an API key in the request header for an MVC web api project.

I see that there is a well outlined example of a MessageHandler for just that purpose in http://www.asp.net/web-api/overview/working-with-http/http-message-handlers

e.g.

GlobalConfiguration.Configuration.MessageHandlers.Add(new ApiKeyHandler());

But it looks like I can do the same thing using a filter as well.

GlobalConfiguration.Configuration.Filters.Add(new ApiKeyFilter());

Assuming ApiKeyFilter and ApiKeyHandler both just look at the request header and check for an api key, Which way is more efficient? What's the difference?

1 Answer 1

6

MessageHandlers run much earlier than filters.

the order is:

-MessageHandler

-Authorization filter

-Model binding

-Other filters

Security related stuff should run as early as possible.

Sign up to request clarification or add additional context in comments.

5 Comments

if I just want to inspect request and response, for example just logging the request and response payload then what should be preferred? because filters and handlers can handle this. Handlers can also be per route specific.So "Security related stuff" is the only differentiator when it comes to the use cases of each?
It is about scoping and about order of execution. Since message handlers seem to go away in vnext - i would rather use Katana middleware for logging.
thanks, I m still confused.Just to get my basics right pls assume for now we don't have katana.if I use filters for logging will there be any disadvantage. I understand that for stuff that needs to executed very early handlers should be used. but assume I don't have any such requirement with logging then which is a better choice(handlers or filters).Logging is just an example I an quoting for the discussion. thanks again
Logging can't be an example - because it depends on what you are doing ;) If you don't care about at which point in the pipeline your code is executed, then it doesn't matter.
Thanks, "If you don't care about at which point in the pipeline your code is executed, then it doesn't matter" answered the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.