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?
This is the current working code:
[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)
{
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…