简体   繁体   English

在ASP.net核心中创建自定义验证属性

[英]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. 用例之一是当接收到请求时,我要确保为旧客户端提供X-Request-For标头,可以正确处理。 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. 还有其他用例,但是所有这些用例都会四处读取特定的http标头值,并在控制器负责之前采取适当的措施。

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

You can create such an attribute using MVC filters . 您可以使用MVC过滤器创建这样的属性。

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). 在此示例中,我使用了ResourceFilter,因为它在管道中处于早期阶段(就在auth之后和模型绑定之前-这对您的情况而言很有意义)。

But depending on what you need to do you should use the appropriate filter. 但是,根据您需要执行的操作,应使用适当的过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM