ASP.NET Core Route attributes available in entire controller class

后端 未结 1 953
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 02:47

Is there a way to make attributes specified in the route available in the whole class? For instance, consider this Controller:

[Route(\"api/store/{storeId}/         


        
相关标签:
1条回答
  • 2020-12-21 03:05

    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);
        }
    }
    

    Or there is a better solution for this using [FromRoute] attribute on a controller property (as desribed here)

    [Route("api/store/{storeId}/[controller]")]
    public class BookController : ControllerBase
    {
        [FromRoute(Name = "storeId")] 
        public int StoreId { get; set; }
    
        [HttpGet("{id:int:min(1)}")]
        public async Task<IActionResult> GetBookById(int id)
        {
            // use value of storeId here
        }       
    }
    
    0 讨论(0)
提交回复
热议问题