我不确定我在这里问的问题是否正确。
我有一个共享页面(母版页),它调用侧面菜单、页眉、页脚等的几个部分页面。并且我的所有 Controller 都继承 BaseController。
现在,根据用户登录状态,我需要在所有这些部分页面中显示不同的数据,我认为检查用户是否登录的最佳位置是 BaseController。
这就是我的问题。我需要联系我的一项网络服务来查看用户是否登录并获取一些相关数据(如果登录)。我只需执行一次此操作,并且由于所有 Controller 都继承自 BaseController,因此每个部分页面调用都会导致 Web 服务调用。
显然,我不能只粘贴一个私有(private) bool 变量isUserAuthenticated
并检查标志,因为每个 Controller 都会有一个基本 Controller 的新实例。
在传统的 asp.net 项目中,我会将这些内容放入 HttpContext.Current.Items[]
中并重复使用它,但我无法(以某种方式)在 MVC 中访问它。
我不能只是不从部分页面上的basepage继承,因为它们也可以独立调用,而且我也需要知道用户登录状态。
仅调用一次函数,或者仅在一次调用期间存储 bool 值的最佳方法是什么? - Controller 之间可访问..
人们如何做到这一点? 谢谢,抱歉,我是 mvc 的新手!
最佳答案
您仍然可以使用 HttpContext.Items
,但您需要通过 HttpContextBase
实例访问它。
为了向后兼容,您可以将 HttpContext
包装在 HttpContextWrapper
中,如下所示
var context = new HttpContextWrapper(HttpContext.Current);
@iamserious 的 answer above建议使用静态属性 - 我强烈不同意。设置静态变量是应用程序范围内的,这意味着每个用户都将使用相同的变量 - 因此所有人都将具有相同的登录数据。您希望将其存储在Session
中的每个用户或通过HttpContext.Items
存储在每个Request
中。
我建议使用类似这种方法,然后无论您在何处调用 ContextStash.GetInstance,您都会在同一请求的生命周期内收到相同的实例。。您也可以遵循相同的模式并使用 HttpContext.Session
而不是 HttpContext.Items
:
// could use this.HttpContext inside a controller,
// or this.Context inside a view,
// or simply HttpContext.Current
var stash = ContextStash.GetInstance(this.HttpContext);
if(!stash.IsSomething)
{
// do something to populate stash.IsSomething
}
// class
public class ContextStash
{
const string cacheKey = "ContextStash";
public ContextStash(HttpContextBase context)
{
// do something with context
}
// your shared properties
public bool IsSomething { get; set; }
public string Foo { get; set; }
public int Bar { get; set; }
// instance methods
public static ContextStash GetInstance()
{
return GetInstance(new HttpContextWrapper(HttpContext.Current));
}
public static ContextStash GetInstance(HttpContext context)
{
return GetInstance(new HttpContextWrapper( context ));
}
public static ContextStash GetInstance(HttpContextBase context)
{
ContextStash instance = context.Items[cacheKey] as ContextStash;
if(null == instance)
{
context.Items[cacheKey] = instance = new ContextStash(context);
}
return instance;
}
}
关于asp.net-mvc - 从基本页面在不同 Controller 之间保留数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7650609/