Validating and passing controller-level parameters with ASP.NET MVC attribute routing

前端 未结 2 1285
别跟我提以往
别跟我提以往 2020-12-12 01:08

I have an ASP.NET controller where every single method will have a shared parameter. With attribute routing, I can add this parameter in the controller\'s route.

Ho

相关标签:
2条回答
  • 2020-12-12 01:43

    As Hooman Bahreini said , you could customize a action filter that inherits ActionFilterAttribute and use it as a attribute on the controller .In Asp.net core , ActionArguments replaces ActionParameters

    public class ValidateNameParameterAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionArguments.ContainsKey("name"))
            {
                string name = filterContext.ActionArguments["name"] as string;
    
                if(name!=null && name.Length>10)
                {
                    filterContext.Result = new BadRequestObjectResult("The length of name must not exceed 10");
                }
            }
        }
    }
    

    For more details on Filters in ASP.NET Core , you could refer to here .

    0 讨论(0)
  • 2020-12-12 01:48

    You can do this using a custom action filter to validate the name parameter:

    public class ValidateNameParameterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionParameters.ContainsKey(name))
            {
                // the trick is to get the parameter from filter context
                string name = filterContext.ActionParameters[name] as string;
    
                // validate name
    
                if (/*name is not valid*/)
                {
                    // you may want to redirect user to error page when input parameter is not valid
                    filterContext.Result = new RedirectResult(/*urlToRedirectForError*/);
                }
    
                base.OnActionExecuted(filterContext);
            }
        }
    }
    

    Now you can apply the filter to your controller, or specific actions:

    [ApiController]
    [Route("[controller]/{name}")]
    [ValidateNameParameter] // <-- execute this for all actions in the controller
    public class ExampleController : ControllerBase
    {
        [HttpGet]
        public string Sample([StringLength(10)][FromRoute]string name)
        {
        }
    
        [HttpGet]
        [Route("defaults")]
        public string GetDefaults([StringLength(10)][FromRoute]string name)
        {
        }
    
        [HttpGet]
        [Route("objects/{id}")]
        // [ValidateNameParameter] // <-- execute for this specific action
        public string Sample([StringLength(10)][FromRoute]string name, [FromRoute]string id)
        {
        }
    }
    

    See this tutorial for more information.

    0 讨论(0)
提交回复
热议问题