【问题标题】:How to write a cookie inside a static method如何在静态方法中写入 cookie
【发布时间】:2013-03-17 17:48:35
【问题描述】:

我需要在静态方法中编写一个 cookie(我需要静态,因为我想从其他类调用此方法)。我找到了HttpContex.Current 的解决方案,但它不适合我。我收到此错误

非静态字段、方法或属性“System.Web.Mvc.Controller.HttpContext.get”需要对象引用

我也尝试添加 using System.Web.HttpContext.Current; 并收到此错误

'System.Web.HttpContext.Current' 是一个“属性”,但用作“类型”

我的方法:

public static void WriteCookie(Guid token)
{ 
    HttpCookie cookie = new HttpCookie("LoginControl");

    cookie.Value = token.ToString();
    cookie.Expires = DateTime.Now.AddHours(0.5);

    HttpContext.Current.Reponse.Cookies.Add(cookie);
}

有什么建议吗? 非常感谢马修。

【问题讨论】:

  • 你有一个错字Reponse应该是Response

标签: c# asp.net static-methods httpcontext


【解决方案1】:

能不能用method参数传递HttpContext?

public static void WriteCookie(HttpContext context, Guid token)
{ 
    HttpCookie cookie = new HttpCookie("LoginControl");

    cookie.Value = token.ToString();
    cookie.Expires = DateTime.Now.AddHours(0.5);

    context.Response.Cookies.Add(cookie);
}

【讨论】:

  • 正是我要说的。
  • 谢谢,但我将在参数context 中插入什么?
猜你喜欢
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-31
  • 2011-09-05
  • 1970-01-01
相关资源
最近更新 更多