我写了自己的自定义属性,该属性来自ActionFilterAttribute,例如[TestAttr]。我覆盖了OnActionExecuting和OnResultExecuted方法。我还添加了一个检查,以确定我的[TestAttr]是否适用于如下所示的控制器方法

public override void OnActionExecuting(ActionExecutingContext context)
{
   if (context.ActionDescriptor is ControllerActionDescriptor)
   {
       //Need to store a variable int x = 100 here which I want to use later on OnResultExecuted method.
       //value of x will keep on changing for different requests.
       //Is there any way to differentiate between two requests when we land here.
   }
}

public override void OnResultExecuted(ResultExecutedContext context)
{
   if (context.ActionDescriptor is ControllerActionDescriptor)
   {
       //Do Desired stuff.
       //Use the value of x
   }
}


基本上,我想做以下
OnActionExecuting方法调用
ActualRestCall
OnResultExecuted方法调用

但是我想在OnActionExecuting调用中存储一个值,然后在OnResultExecuted方法中使用它。并且这不应覆盖多个请求中的值。

最佳答案

您可以使用HttpContext.Items存储值,以便稍后在请求流中使用。例如:

public class FooAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Store the value...
        context.HttpContext.Items.Add("MyValue", 100);

        base.OnActionExecuting(context);
    }

    public override void OnResultExecuted(ResultExecutedContext context)
    {
        // Retrieve the value...
        if (context.HttpContext.Items.TryGetValue("MyValue", out var value))
        {
            // We know this is an int so cast it
            var intValue = (int)value;
        }

        base.OnResultExecuted(context);
    }
}

关于c# - 如何在C#中的ActionFilterAttribute的OnActionExecuting中区分两个Rest调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57688633/

10-09 22:54