3

I want to use attribute to make sure certain headers are present in my request. This is not an authorize attribute. One of the use case is when a request is received, I want to make sure that there is X-Request-For header for older clients, that can be handled properly. There are other use cases aswell, however all of them go around reading a specific http header value and taking appropriate action before controller takes the charge.

[MyAttribute(HeaderOptions.RequestFor)
[httpPost]
public MyMethod(string data) 
{
...
}
0

1 Answer 1

9

You can create such an attribute using MVC filters.

For example create a filter like this:

public class CheckHeaderFilter : Attribute, IResourceFilter
{
    private readonly string[] _headers;

    public CheckHeaderFilter(params string[] headers)
    {
        _headers = headers;
    }

    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        if (_headers == null) return;
        
        if (!_headers.All(h => context.HttpContext.Request.Headers.ContainsKey(h)))
        {
            //do whatever you need to do when check fails
            throw new Exception("Necessary HTTP headers not present!");
            
        }
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
        
    }
}

and then use it on an action (or controller):

[CheckHeaderFilter(HeaderOptions.RequestFor)]
public IActionResult Index()
{
   ...
}

I strongly recommend you read through the docs, so you know which type of filter to use. In this example I used ResourceFilter as it's fairly early in the pipeline (right after auth and before model binding - which makes sense for your scenario).

But depending on what you need to do you should use the appropriate filter.

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

1 Comment

Works good, but returns a 500 status code to client instead of a 4xx, since this is a client side error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.