Asp.net mvc 3 ASP.NET MVC-访问非控制器类中的Cookie数据

Asp.net mvc 3 ASP.NET MVC-访问非控制器类中的Cookie数据,asp.net-mvc-3,Asp.net Mvc 3,我需要编写一个函数来帮助我在一些控制器中执行某些操作,因此我决定为此创建一个名为Helper的类 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

我需要编写一个函数来帮助我在一些控制器中执行某些操作,因此我决定为此创建一个名为Helper的类

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);
        }
    }
}
问题是我无法再访问请求或响应

请给我指路

您可以在助手类中使用
HttpContext.Current.Request
HttpContext.Current.Response

这与访问会话基本相同。使用httpcontext.current,尽管有时会有人反对它,但这里提到要清理它:


在这里,您可以定义像IRequest这样的接口来抽象出具体的实现,但这取决于您。

虽然第一个答案在技术上是准确的,但我遇到了与使用外部.DLL创建cookie不一致的问题。代码隐藏类调用external.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;
    }