2

我正在尝试在一个静态类上构建一个静态属性,该属性基本上会返回一个 cookie 值,以便在我的 MVC 站点(MVC 3,如果重要的话)中使用。像这样的东西:

public static class SharedData
{
    public static string SomeValue
    {
        get
        {
            if (HttpContext.Current.Request.Cookies["SomeValue"] == null)
            {
                CreateNewSomeValue();
            }

            return HttpContext.Current.Request.Cookies["SomeValue"].Value.ToString();
        }
    }
}

我需要从控制器操作、global.asax 方法和操作过滤器中访问它。但问题是,当动作过滤器运行时,HttpContext 不可用。现在,我必须有一个单独的静态方法才能从我传入的过滤器上下文中提取 cookie,这看起来很尴尬。

构建这样一个静态方法来检索这样的 cookie 值的最佳解决方案是什么,该方法适用于控制器操作和操作过滤器?或者有没有更好的方法来做这样的事情?

提前致谢。

4

2 回答 2

2

对静态的调用HttpContext.Current不是好的设计。HttpContext相反,创建一个扩展方法来从and的实例访问 cookie HttpContextBase

我为你写了一个小助手。您可以使用它在操作过滤器中执行您的功能。

public static class CookieHelper
{
    private const string SomeValue = "SomeValue";
    public static string get_SomeValue(this HttpContextBase httpContext)
    {
        if(httpContext.Request.Cookies[SomeValue]==null)
        {
            string value = CreateNewSomeValue();
            httpContext.set_SomeValue(value);
            return value;
        }
        return httpContext.Request.Cookies[SomeValue].Value;
    }
    public static void set_SomeValue(this HttpContextBase httpContext, string value)
    {
        var someValueCookie = new HttpCookie(SomeValue, value);
        if (httpContext.Request.Cookies.AllKeys.Contains(SR.session))
        {
            httpContext.Response.Cookies.Set(someValueCookie);
        }
        else
        {
            httpContext.Response.Cookies.Add(someValueCookie);
        }
    }   
}

注意:您可以轻松地使这些方法起作用,只需将参数HttpContext替换为.HttpContextBaseHttpContext

于 2011-03-20T03:57:30.223 回答
1

正如上面 JohnnyO 所指出的,我一直可以从我的操作过滤器中访问 HttpContext。至少,在需要这样做的特定动作过滤器方法中。可能有一些其他过滤器/方法在某一时刻无法访问,但现在,它正在按我的需要工作。

于 2011-03-21T06:09:57.127 回答