【问题标题】:Handling cookies in a seperate class file in C# ASP.NET MVC在 C# ASP.NET MVC 中的单独类文件中处理 cookie
【发布时间】:2016-03-16 20:23:07
【问题描述】:

我已经制作了一个单点登录系统,并且正在制作一个用于处理 cookie 的类库。 但我无法将服务器(ASP.NET MVC 控制器)实例放入类库中。 请在附件中找到我的 .cs 文件,其中我有可以处理我的应用程序中所有 cookie 的方法。 我应该将 HTTPContext 对象从我的 Web 应用程序传递到类库(到方法中)还是 Response 对象? 我都试过了,但都是徒劳的!

public void DoLogin(string username, bool autoSignIn)
{
    HttpContext.Current.Response.Cookies["nowenableLogin"]["username"] = username;
    HttpContext.Current.Response.Cookies["nowenableLogin"]["autoSignIn"] = autoSignIn.ToString();
    HttpContext.Current.Response.Cookies["nowenableLogin"]["lastVisit"] = DateTime.Now.ToString();
    HttpContext.Current.Response.Cookies["nowenableLogin"]["status"] = true.ToString();
    HttpContext.Current.Response.Cookies["nowenableLogin"].Expires = autoSignIn ? DateTime.Now.AddDays(7) : DateTime.Now.AddDays(1);
}

【问题讨论】:

  • 你不能这样做,除非你将控制器中的HttpContext 注入到类中。
  • 有没有办法将 HttpContext 注入到类中?
  • 您可以只添加一个参数public void DoLogin(string username, bool autoSignIn, HttpContext context),但我怀疑您最好将此方法移动到BaseController : Controller 类(可以访问HttpContext)并拥有所有控制器需要访问它的它继承自BaseController
  • 感谢您的建议......

标签: c# asp.net asp.net-mvc asp.net-mvc-4 cookies


【解决方案1】:

我在尝试读取“cshtml”文件时遇到了同样的问题。 我将它保存在一个变量中,并在电子邮件中将其作为正文发送。我解决的方法 它是通过在 控制器类(帮助类中的方法被称为给予 它的参数)。但是在这种情况下,你只需要HttpContext,所以替换我对ControllerContext的想法,这样它就会使用

控制器中的这个 sn-p:

 HelperClass.DoLogin("username",true,HttpContext.Current);

然后,在辅助类中你可以使用:

public void DoLogin(string username, bool autoSignIn,HttpContext context)
{
     var cookie = context.Response.Cookies["cookieName"];
}

【讨论】:

    猜你喜欢
    • 2013-07-03
    • 2012-04-18
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2013-08-27
    • 1970-01-01
    相关资源
    最近更新 更多