【发布时间】:2016-04-20 17:01:35
【问题描述】:
我正在 DotVVM 中构建站点,当我尝试以下代码行但出现错误时:NullReferenceException
HttpContext.Current.Session.Add ("Value", Item3);
【问题讨论】:
我正在 DotVVM 中构建站点,当我尝试以下代码行但出现错误时:NullReferenceException
HttpContext.Current.Session.Add ("Value", Item3);
【问题讨论】:
DotVVM 是一个OWIN 中间件,因此您必须先配置OWIN 才能启用会话。首先,您需要声明这个方法,它会打开 ASP.NET 会话:
public static void RequireAspNetSession(IAppBuilder app) {
app.Use((context, next) =>
{
var httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
return next();
});
// To make sure the above `Use` is in the correct position:
app.UseStageMarker(PipelineStage.MapHandler);
}
然后在Startup.cs文件中,调用它:
app.RequireAspNetSession();
然后您可以使用HttpContext.Current.Session["key"] 访问您的会话状态。
【讨论】:
您可以通过以下方式将对象保存在 Session 中:
Session["Value"] = Item3;
您可以通过以下方式从 Session 中检索对象:
object value = Session["Value"];
通常,您需要将值转换为您使用的类型,因此如果Item3 是一个字符串,那么您会这样做:
string value = (string)Session["Value"];
您也可以从视图中访问会话变量,因此您不需要将其存储在视图模型中。
【讨论】: