如何传递HttpContext.Current函数?

How to pass HttpContext.Current to function?

在我的控制器操作中,我想使用功能来设置 cookie(如果未安装),并在缓存中添加一些数据。

控制器

    [HttpGet]
    [ActionName("Search")]
    public ActionResult SearchGet(SellsLiveSearch Per, int page)
    { if (HttpContext.Request.Cookies["G"] != null)
         {...}
       else
         {SearchFunc(Per);}
    }

    public static List<SellsLive> SearchFunc(SellsLiveSearch Per)
    {...
     System.Web.HttpContext.Current.Response.SetCookie(cookie);
     HttpContext.Cache.Add
           (
             Key,
             Data,
             null,
             DateTime.Now.AddMinutes(30),
             TimeSpan.Zero,
             System.Web.Caching.CacheItemPriority.Normal,
             null
           );
    }

但是我做不到,因为 VS 报错:

HttpContextBaseController.HttpContext

错误:

对于非静态字段,方法或 属性 "System.Web.Mvc.Controller.HttpContext.get" 需要对象引用。

我做错了什么,我需要做什么?

我有以下设置cookies的代码,你不妨试试:

    public void SetCookie(string key, string value, TimeSpan expires, bool isHttpOnly)
    {
        var encodedCookie = new HttpCookie(key, value);

        encodedCookie.HttpOnly = isHttpOnly;

        if (HttpContext.Current.Request.Cookies[key] != null)
        {
            var cookieOld = HttpContext.Current.Request.Cookies[key];
            cookieOld.Expires = DateTime.Now.Add(expires);
            cookieOld.Value = encodedCookie.Value;
            HttpContext.Current.Response.Cookies.Add(cookieOld);
        }
        else
        {
            encodedCookie.Expires = DateTime.Now.Add(expires);
            HttpContext.Current.Response.Cookies.Add(encodedCookie);
        }
    }

您可以将上下文传递给函数或使用 HttpContext.Current 检索当前上下文。

传入

public static List<SellsLive> SearchFunc(SellsLiveSearch Per, HttpContext context)
{
    context.Response.SetCookie(cookie);
}

并这样称呼它:

SearchFunc(Per, this.HttpContext);

获取当前上下文

public static List<SellsLive> SearchFunc(SellsLiveSearch Per)
{
    HttpContext context = HttpContext.Current;
    context.Response.SetCookie(cookie);
    //etc
}

当然,这种方法只有在函数 运行 在正确的线程上才有效。