是否有一种方法可以使路由中指定的属性在整个类中可用?例如,考虑以下控制器:
[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
}
}
答案 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);
}
}