ASP.NET Core自定义验证属性未触发

时间:2018-10-09 03:16:42

标签: c# asp.net-core custom-attributes validationattribute

我在API Controller中有一个GET方法。我希望使用自定义验证属性来验证该方法,如下所示。但是由于某些原因,它没有被解雇。

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class CheckValidRoute : ValidationAttribute
    {
        private readonly string _apiRoute;
        private readonly string _operation;

        public override bool RequiresValidationContext { get { return true; } }

        public CheckValidRoute(string apiRoute, string operation)
        {
            _apiRoute = apiRoute;
            _operation = operation;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
           //Validation logic here
        }
    }

控制器

public class TestController : ControllerBase
    {
        [HttpGet("production/{movieId}/Test")]
        [ProducesResponseType(typeof(ResponseModel<string>), 200)]
        [Authorize(Policy = SecurityConstants.PseudofilmAuthorizationPolicy)]
        [CheckValidRoute("production/{movieId}/Test", "GET")]
        public async Task<ResponseModel<string>> TestGet(long movieId)
        {
            return ResponseModelHelper.BuildResponse("Success", $"production/{movieId}/Test", "Test");
        }
    }

我不确定我在这里缺少什么。

-艾伦-

1 个答案:

答案 0 :(得分:4)

您使用了错误的基类来实现您的属性。 ValidationAttribute上使用Models来验证其属性值。例如Required属性。

在您的情况下,您想实现一个ActionFilter,它可以应用于控制器方法,并且可以在调用该方法之前执行验证。一个适合您的示例是:

public class CheckValidRouteAttribute : ActionFilterAttribute
{
    private readonly string _apiRoute;
    private readonly string _operation;

    public CheckValidRouteAttribute(string apiRoute, string operation) : base()
    {
        _apiRoute = apiRoute;
        _operation = operation;
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var request = context.HttpContext.Request;

        var method = request.Method;

        if (string.Compare(method, _operation, true) != 0)
        {
            context.Result = new BadRequestObjectResult("HttpMethod did not match");
        }
    }
}

OnActionExecuting方法中,您可以对HttpContext.Request对象执行检查。我把它留给您作为练习,因为我不知道您的确切要求:-)

将此属性应用于控制器方法后,将在调用控制器方法之前调用OnActionExecuting,以便您进行验证。

您可以了解有关ActionFilters here

的更多信息