簡體   English   中英

在 OnActionExecuting 上獲取操作參數

[英]Get action parameter on OnActionExecuting

使用 .NET 核心 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();
    }
}

我在這里缺少什么嗎? 因為我讀了幾篇文章,他們已經提到了上面的內容。

我相信您可以使用以下內容。 我在日志過濾器中使用了類似於下面的內容。 日志過濾器代碼也在下面。 您也可以迭代集合。

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

遍歷所有參數並將它們聚合到最終寫入文件的日志字符串中。

logString = filterContext.ActionParameters.Aggregate(logString, (current, p) => current + (p.Key + ": " + p.Value + Environment.NewLine));

對於在查詢字符串中傳遞的參數,請使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM