2

我有一个 MVC 应用程序,其中控制器 A 调用内部 HTTPGET 方法(由控制器 B 处理)。A有观点,B没有。

控制器 B 中的 HTTPGET 如下所示:

[HttpGet]
public String GetToken(string accessToken, string UID)  {
    ....
    // Log errors and other metrics
    return someToken;
}

我想在我的 B 控制器上使用一个动作过滤器,它为我记录错误。我确实需要在记录时使用 HTTP GET 传递的参数。如何将 accessToken 和 UID 传递给操作过滤器以便我可以记录它。

我正在寻找的是这样的:控制器应该是这样的

[MyActionFilter]
[HttpGet]
public String GetToken(string accessToken, string UID)  {
        ....
        return someToken;
    }

而动作过滤器应该做日志记录

public class MyActionFilterAttribute : ActionFilterAttribute {
    public override void onActionExecuted(HttpActionExecutedContext actionExecutedContext) {
        // READ THE HTTP GET PARAMETERS AND DO THE LOGGING
    }
}
4

3 回答 3

3

你可以使用这个:

public class MyActionFilterAttribute : ActionFilterAttribute {
    public override void onActionExecuted(
                                  ActionExecutedContext actionExecutedContext) {
        // READ THE HTTP GET PARAMETERS AND DO THE LOGGING
        actionExecutedContext.HttpContext.Request.QueryString; // HTTP GET 
       actionExecutedContext.HttpContext.Request.Params; 
       // HTTP GET / POST / COOKIE PARAMETERS As Key Value List
    }
}
于 2013-08-22T09:23:04.843 回答
1

最好的方法是按照其他答案的建议记录 QueryString 和其他项目,但是如果您只想访问方法参数,那么您可以如下所示进行操作,ActionParameters Dictionary 将为您提供所有方法参数。

public class MyActionFilterAttribute : ActionFilterAttribute {
    public override void OnActionExecuted
       (HttpActionExecutedContext filterContext) {
        foreach (KeyValuePair<string,object> item 
            in filterContext.ActionParameters)
        {
            //print item.Key
            //print item.Value
        }
    }
}
于 2013-08-27T17:34:51.947 回答
-1

我通过在控制器中公开所需参数并直接将参数读取为filterContext.Controller.publicParam.

ActionFilter 现在看起来像这样 -

public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var thisController = ((myController)filterContext.Controller);

        // public function in the controller that returns the required object
        RequiredParameters requiredParams = 
                                    thisController.getParametersForLogging( );

        // read the variables from requiredParams object and do the logging
    }
于 2013-08-23T05:23:27.460 回答