【问题标题】:Find route variables from attribute从属性中查找路由变量
【发布时间】:2019-01-22 16:39:55
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: asp.net-core routing asp.net-mvc-routing


    【解决方案1】:

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

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

    【讨论】:

    • 最后我使用了另一种方法,因为我使用了更复杂的路线,但这按预期工作。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2017-08-16
    • 1970-01-01
    • 2013-11-08
    • 2016-09-09
    • 2015-01-04
    • 1970-01-01
    相关资源
    最近更新 更多