问题
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}/[controller]")]
public class BookController
{
[HttpGet("{id:int:min(1)}")]
public async Task<IActionResult> GetBookById(int storeId, int id)
{
}
}
And this request:
/api/store/4/book/1
Inside the GetBookById method, the storeId variable is correctly populated with 4 and the id variable with 1. However, instead of having to pass the storeId variable in every method of the BookController, is there a way to do something like this:
[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:
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);
}
}
来源:https://stackoverflow.com/questions/55179643/asp-net-core-route-attributes-available-in-entire-controller-class