我尝试在静态类上构建一个静态属性,该属性基本上会返回一个 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
的调用不是一个好的设计。相反,创建一个扩展方法来从 HttpContext
和 HttpContextBase
的实例访问 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/