Asp.net 如何将HttpContext.Current传递给函数?

Asp.net 如何将HttpContext.Current传递给函数?,asp.net,asp.net-mvc,asp.net-mvc-4,Asp.net,Asp.net Mvc,Asp.net Mvc 4,在控制器的操作中,我想使用函数设置未安装的cookie,并在缓存中添加一些数据 控制器 [HttpGet] [ActionName("Search")] public ActionResult SearchGet(SellsLiveSearch Per, int page) { if (HttpContext.Request.Cookies["G"] != null) {...} else {SearchFunc(

在控制器的操作中,我想使用函数设置未安装的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
           );
    }
[HttpGet]
[ActionName(“搜索”)]
public ActionResult SearchGet(每页的SellsLiveSearch,整页)
{if(HttpContext.Request.Cookies[“G”!=null)
{...}
其他的
{SearchFunc(Per);}
}
公共静态列表搜索函数(SellsLiveSearch Per)
{...
System.Web.HttpContext.Current.Response.SetCookie(cookie);
HttpContext.Cache.Add
(
钥匙
数据,
无效的
DateTime.Now.AddMinutes(30),
时间跨度0,
System.Web.Caching.CacheItemPriority.Normal,
无效的
);
}
但我不能这样做,因为VS给出了错误:

HttpContextBase控制器.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
检索当前上下文

传过来 获取当前上下文
publicstaticlist SearchFunc(SellsLiveSearch Per)
{
HttpContext=HttpContext.Current;
context.Response.SetCookie(cookie);
//等
}

当然,只有当函数在正确的线程上运行时,这种方法才会起作用。

第二种方法是这样工作的:HttpContext=System.Web.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
}