ASP.NET Core Route attributes available in entire controller class

久未见 提交于 2019-12-01 23:10:33

If the controller inherits from Controller class then you can override OnActionExecuting method, if the controller inherits from ControllerBase you need to implement IActionFilter interface to make it work

[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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!