Jay Bee
Jay Bee

Reputation: 35

create custom validation attribute in ASP.net core

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) 
{
...
}

Upvotes: 3

Views: 11234

Answers (1)

erikbozic
erikbozic

Reputation: 1665

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.

Upvotes: 9

Related Questions