简体   繁体   中英

How do I create a custom api parameter validation attribute which returns bad request on aspnet core 3?

I have the following endpoint in my controller, and I would like to create a custom validation for attribute passed from query.

[ApiController]
public class SampleController : ControllerBase
{
    [HttpGet]
    [Route("api/user")]
    public IActionResult GetUsersByLevel(
        [BindRequired, ValidLevelFromQuery(Name = "level")] string level)
    {
        ...
    }
}

My desired outcome is that I create a custom FromQuery attribute, which in this sample I describe as ValidLevelFromQuery . The custom attribute would check the value of level and would only accept "A", "B", and "C" , on any other value, the response to the client will be a BadRequest .

Currently I am doing the validation after I have read the value in the action. My goal is have this check earlier in the request pipeline.

I would like to avoid using IValidatableObject if possible.

You can use ActionFilter to achieve this.

Please refer to the following code:

        [HttpGet]
        [Route("api/user")]
        [ValidLevelFromQuery]
        public IActionResult GetUsersByLevel(
           [BindRequired] string level)
        {
            return Ok();
        }

ValidLevelFromQuery method:

public class ValidLevelFromQueryAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Validates Level automaticaly
        /// </summary>
        /// <param name="context"></param>
        /// <inheritdoc />
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ActionArguments.ContainsKey("level"))
            {
                string[] allowedGroup = new string[] { "A", "B", "C" };
                if (!allowedGroup.Contains(context.ActionArguments["level"]))
                {
                    context.Result = new BadRequestObjectResult("The level is not allowed");
                }
            }
        }

Here is the test result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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