从属性中查找路由变量

Find route variables from attribute

我想用 1 个路由参数自动填充 ViewContext,但有时它在查询中,有时它在 Url。

在查询时,使用req.Query.TryGetValue(key, out StringValues val)很容易得到参数。 但是我正在寻找一种方法来捕获这样的路由参数:

[PrefillViewContext("postId")]
[HttpGet("/Post/{postId}")]
public IActionResult DisplayPost(Guid postId) {}

有没有办法在方法体之外获取这个 postId 值,并在上面的属性中使用它? (或在 class 级别的属性中)

您可以通过继承 ActionFilterAttribute 使用 ActionExecutingContext 获取操作参数。您可以从上下文中获取所有 RouteData。

public class PrefillViewContextAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var postId = context.ActionArguments["PostId"];
    }

}