如何在DotVVM viewmodel中创建会话变量?

Tom*_*sek 4 asp.net session dotvvm

我正在DotVVM中构建一个站点,当我尝试以下代码行但我收到错误:NullReferenceException

HttpContext.Current.Session.Add ("Value", Item3);
Run Code Online (Sandbox Code Playgroud)

Tom*_*ceg 7

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);
}
Run Code Online (Sandbox Code Playgroud)

然后在Startup.cs文件中调用它:

app.RequireAspNetSession();
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用HttpContext.Current.Session["key"]访问您的会话状态.