小编Wie*_*hie的帖子

使用 ASP.NET MVC 属性路由验证和传递控制器级参数

我有一个 ASP.NET 控制器,其中每个方法都有一个共享参数。通过属性路由,我可以在控制器的路由中添加这个参数。

但是,我仍然需要在每个方法中添加该参数以及验证属性。有没有办法让我在一个地方进行验证或避免将其传递给每个方法?

这是当前的工作代码:

[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)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

有可能得到接近于此的东西吗?(我知道控制器上的验证参数无效,但我只想应用一次)

[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)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc asp.net-web-api asp.net-core

4
推荐指数
2
解决办法
5584
查看次数

标签 统计

asp.net-core ×1

asp.net-mvc ×1

asp.net-web-api ×1

c# ×1