有没有办法让路由中指定的属性在整个类中可用?例如,考虑这个控制器:
[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 方法中,storeId 变量正确填充为 4,id 变量填充为 1。但是,不必在 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
}
}
如果控制器继承自Controller
类然后你可以覆盖OnActionExecuting
方法,如果控制器继承自ControllerBase
你需要实施IActionFilter
使其工作的接口
[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);
}
}
或者有更好的解决方案使用[FromRoute]
控制器属性上的属性(如所描述的here https://stackoverflow.com/a/60078086/7775908)
[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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)