[英]How to pass HttpContext.Current to function?
In my action of controller i want to use function for to set cookies if they are not installed, and to add in cache some data. 在控制器的动作中,我想使用函数来设置未安装的cookie,并在缓存中添加一些数据。
Controller 调节器
[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
);
}
But i can't do this, because VS gives error: 但是我不能这样做,因为VS给出了错误:
HttpContextBase Controller.HttpContext HttpContextBase Controller.HttpContext
Error: 错误:
For the nonstatic field, method or property "System.Web.Mvc.Controller.HttpContext.get" requires an object reference. 对于非静态字段,方法或属性“ System.Web.Mvc.Controller.HttpContext.get”需要对象引用。
What am i doing wrong and what i need to do? 我做错了什么,我需要做什么?
You can either pass the context into the function or use HttpContext.Current
to retrieve the current context. 您可以将上下文传递到函数中,也可以使用
HttpContext.Current
检索当前上下文。
public static List<SellsLive> SearchFunc(SellsLiveSearch Per, HttpContext context)
{
context.Response.SetCookie(cookie);
}
And call it like this: 并这样称呼它:
SearchFunc(Per, this.HttpContext);
public static List<SellsLive> SearchFunc(SellsLiveSearch Per)
{
HttpContext context = HttpContext.Current;
context.Response.SetCookie(cookie);
//etc
}
Of course, this way will only work if the function is running on the correct thread. 当然,只有当函数在正确的线程上运行时,这种方式才有效。
I have got following code to set cookies, you may want to try it: 我有以下代码来设置cookie,您可能想尝试一下:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.