asp.net-mvc - 有关 HttpContext、HttpContextBase 和操作过滤器的问题

标签 asp.net-mvc asp.net-mvc-3 httpcontext action-filter

我尝试在静态类上构建一个静态属性,该属性基本上会返回一个 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();
        }
    }
}

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

构建这样一个静态方法来检索像这样从 Controller 操作和操作过滤器中都起作用的 cookie 值的最佳解决方案是什么?或者有更好的方法来做这样的事情吗?

提前致谢。

最佳答案

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

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

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 上工作,只需将 HttpContextBase 参数替换为 HttpContext 即可。

关于asp.net-mvc - 有关 HttpContext、HttpContextBase 和操作过滤器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5366642/

相关文章:

c# - ASP.NET MVC3 WebGrid 格式 : parameter

asp.net-mvc - 使用无障碍 JQuery 在部分 View 中显示错误消息时遇到问题

c# - 静态方法中的 HttpContext.Current.Response

javascript - HttpContext.Request.Browser.Browser 将 Edge 检测为 Chrome

asp.net-mvc - 在 ASP.NET MVC Web 应用程序中托管 WCF 服务

asp.net-mvc - 测试从 ASP.NET MVC 应用程序返回的 HTTP header

jquery - Javascript 在 TextBox + MVC3 中禁用空格键

c# - MVC4 中从 View 到 Controller 的 JSTree 调用

asp.net-mvc - Recaptcha for .NET MVC 在使用 SSL 时遇到更多麻烦

asp.net-mvc - 为什么 HttpContext.Request.Url 与地址栏中的内容不匹配?