2011-11-05 73 views
3

我需要編寫一個幫助我在某些控制器中執行某些操作的函數,因此我決定創建一個名爲Helper的類。ASP.NET MVC - 訪問非控制器類中的Cookie數據

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Security; 

namespace HocVuiDiary.Helper 
{ 
    public class CookiesHelper 
    { 
     public void UpdateSubkey(string name, string subkey, string subvalue) 
     { 
      HttpCookie cookie; 
      if (Request.Cookies[name] == null) 
      { 
       cookie = new HttpCookie(name); 
       cookie[subkey] = subvalue; 
      } 
      else 
      { 
       cookie = Request.Cookies[name]; 
       cookie[subkey] = subvalue; 
      } 
      cookie.Expires = DateTime.Now.AddDays(30); 
      Response.Cookies.Add(cookie); 
     } 
    } 
} 

問題是我無法訪問請求或響應更多!
請告訴我正確的方法!

回答

8

您可以在助手類中使用HttpContext.Current.RequestHttpContext.Current.Response

0

它與訪問會話基本相同。使用httpcontext.current儘管它是建立在次皺起了眉頭有在這裏提到清除它的: Can I use ASP.NET Session[] variable in an external DLL

在這裏,你可以這樣定義IRequest一個接口來抽象的具體實施了,但一切由你。

3

雖然第一個答案在技術上是準確的,但我遇到了與使用外部.DLL創建cookie不一致的問題。類後面的代碼調用外部.dll中的方法,創建cookie,但是在導航到下一頁後,cookie有時不存在。

public void CreateCookie(string cookieName, string key, string value) 
    { 
     int minutes = 95; 
     string encryptedValue = utilities.EncryptString(value); 
     HttpCookie cookie = new HttpCookie(cookieName); 
     cookie[key] = encryptedValue; 
     cookie.Expires = DateTime.Now.AddMinutes(minutes); 
     HttpContext.Current.Response.Cookies.Add(cookie); 
    } 

對外部類的其他調用按預期工作。

public bool CheckCookieExists(string cookieName) 
    { 
     bool exists = true; 
     HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName]; 
     if (cookie != null) 
     { 
      return exists; 
     } 
     return exists = false; 
    } 
相關問題