使用ASP.NET MVC属性路由验证和传递控制器级别的参数 [英] Validating and passing controller-level parameters with ASP.NET MVC attribute routing
问题描述
我有一个ASP.NET控制器,其中的每个方法都将具有一个共享参数.使用属性路由,我可以在控制器的路由中添加此参数.
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.
但是,我仍然需要在每个方法中都添加该参数以及一个验证属性.我有办法在一个地方进行验证,还是避免将其传递给每种方法?
However, I still need to add that parameter along with a validation attribute in every single method. Is there a way for me to do the validation in one place or avoid having to pass it in to every single method?
这是当前的工作代码:
[ApiController]
[Route("[controller]/{name}")]
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}")]
public string Sample([StringLength(10)][FromRoute]string name, [FromRoute]string id)
{
}
}
是否有可能得到与此相似的东西? (我知道控制器上的验证参数无效,但我只想应用一次)
Is it possible to get something close to this? (I know the validation parameter on the controller is invalid, but I'd like to just have to apply it once)
[ApiController]
[StringLength(10)]
[Route("[controller]/{name}")]
public class ExampleController : ControllerBase
{
[HttpGet]
public string Sample()
{
}
[HttpGet]
[Route("defaults")]
public string GetDefaults()
{
}
[HttpGet]
[Route("objects/{id}")]
public string Sample([FromRoute]string id)
{
}
}
推荐答案
您可以使用自定义操作过滤器来验证name参数:
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.
这篇关于使用ASP.NET MVC属性路由验证和传递控制器级别的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!