获取onOnActionExecuting上的action参数

问题描述 投票:1回答:2

使用.net core mvc c#

我有一个控制器:

[ServiceFilter(typeof(MyCustomFilter))]
public class HomeController : Controller
{
    public IActionResult Index(string type)
    {

    }
}

在我的过滤器中,我希望获得字符串“type”值,因为它作为查询字符串传递

我的过滤器为:

  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MyCustomFilter: ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
          //this is always null
           string id = filterContext.RouteData.Values["type"].ToString();
    }
}

我在这里失踪的任何东西。因为我阅读了很少的帖子,他们已经提到了上述内容。

谢谢

c# asp.net-core asp.net-core-mvc
2个回答
1
投票

对于在查询字符串中传递的参数:

string id = filterContext.Request.Query["type"];

1
投票

我相信你可以使用类似下面的内容。我在日志记录过滤器中使用类似于下面的内容。日志过滤器代码也在下面。您也可以迭代集合。

string id = filterContext.ActionParameters["Type"];

迭代所有参数并将它们聚合到最终写入文件的日志字符串中。

logString = filterContext.ActionParameters.Aggregate(logString, (current, p) => current + (p.Key + ": " + p.Value + Environment.NewLine));
© www.soinside.com 2019 - 2024. All rights reserved.