我有一个 ASP.NET Controller ,其中每个方法都有一个共享参数。通过属性路由,我可以在 Controller 的路由中添加此参数。
但是,我仍然需要在每个方法中添加该参数以及验证属性。有没有一种方法可以让我在一个地方进行验证或避免将其传递给每个方法?
这是当前的工作代码:
[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)
{
}
}
是否有可能得到接近于此的东西? (我知道 Controller 上的验证参数无效,但我只想应用一次)
[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)
{
}
}
最佳答案
您可以使用自定义操作过滤器来验证名称参数来执行此操作:
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);
}
}
}
现在您可以将过滤器应用到 Controller 或特定操作:
[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)
{
}
}
参见this tutorial了解更多信息。
关于c# - 使用 ASP.NET MVC 属性路由验证和传递 Controller 级参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58208688/