整个控制器类中都可以使用ASP.NET Core Route属性 [英] ASP.NET Core Route attributes available in entire controller class
问题描述
是否有一种方法可以使路由中指定的属性在整个类中可用?例如,考虑以下控制器:
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)
{
}
}
这个请求:
/api/store/4/book/1
在GetBookById方法内,storeId变量正确地填充了4,而id变量正确地填充了1.但是,不必在BookController的每个方法中都传递storeId变量,而是可以执行以下操作:
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
}
}
推荐答案
如果控制器继承自Controller
类,则可以覆盖OnActionExecuting
方法,如果控制器继承自ControllerBase
,则需要实现IActionFilter
使其正常工作的界面
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);
}
}
或者在控制器属性上使用[FromRoute]
属性对此有更好的解决方案(如在此处所述)
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
}
}
这篇关于整个控制器类中都可以使用ASP.NET Core Route属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!