【问题标题】:How to differentiate between two rest calls in C# in OnActionExecuting of ActionFilterAttribute如何在 ActionFilterAttribute 的 OnActionExecuting 中区分 C# 中的两个休息调用
【发布时间】:2019-08-28 08:59:42
【问题描述】:

我已经编写了我自己的自定义属性,派生自 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 方法调用 实际休息调用 OnResultExecuted 方法调用

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

【问题讨论】:

  • 我可以将值存储在缓存中或某处,前提是稍后我可以为该请求获取确切的值。

标签: c# asp.net asp.net-web-api asp.net-core-2.1


【解决方案1】:

您可以使用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);
    }
}

【讨论】:

    猜你喜欢
    • 2017-10-14
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多