整个控制器类中都可用的ASP.NET核心路由属性

时间:2019-03-15 09:42:27

标签: c# asp.net asp.net-mvc asp.net-core-2.0 asp.net-core-2.2

是否有一种方法可以使路由中指定的属性在整个类中可用?例如,考虑以下控制器:

[Route("api/store/{storeId}/[controller]")]
public class BookController
{
    [HttpGet("{id:int:min(1)}")]
    public async Task<IActionResult> GetBookById(int storeId, int id)
    {
    }
}

这个请求:

/api/store/4/book/1

在GetBookById方法中,正确地用4填充了storeId变量,并用1填充了id变量。但是,除了必须在BookController的每个方法中传递storeId变量之外,还有一种方法可以执行以下操作:

[Route("api/store/{storeId}/[controller]")]
public class BookController
{
    private int storeId;

    [HttpGet("{id:int:min(1)}")]
    public async Task<IActionResult> GetBookById(int id)
    {
        //use value of storeId here
    }
}

1 个答案:

答案 0 :(得分:2)

如果控制器继承自Controller类,则可以覆盖OnActionExecuting方法,如果控制器继承自ControllerBase,则需要实现IActionFilter接口以使其起作用< / p>

[Route("api/store/{storeId}/[controller]")]
public class BookController : ControllerBase, IActionFilter
{
    private int storeId;

    [HttpGet("{id:int:min(1)}")]
    public async Task<IActionResult> GetBookById(int id)
    {
        // use value of storeId here
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        //empty
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        string value = context.RouteData.Values["storeId"].ToString();
        int.TryParse(value, out storeId);
    }
}