【问题标题】:How do I create a session variable in DotVVM viewmodel?如何在 DotVVM 视图模型中创建会话变量?
【发布时间】:2016-04-20 17:01:35
【问题描述】:

我正在 DotVVM 中构建站点,当我尝试以下代码行但出现错误时:NullReferenceException

HttpContext.Current.Session.Add ("Value", Item3);

【问题讨论】:

    标签: asp.net session dotvvm


    【解决方案1】:

    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"] 访问您的会话状态。

    【讨论】:

      【解决方案2】:

      您可以通过以下方式将对象保存在 Session 中:

      Session["Value"] = Item3;
      

      您可以通过以下方式从 Session 中检索对象:

      object value = Session["Value"];
      

      通常,您需要将值转换为您使用的类型,因此如果Item3 是一个字符串,那么您会这样做:

      string value = (string)Session["Value"];
      

      您也可以从视图中访问会话变量,因此您不需要将其存储在视图模型中。

      【讨论】:

      • 在经典的 asp.net 中是的,但我使用的是新的 asp.net 框架 dotVVM。抱歉,我稍后再写。
      • @TomášJurásek 啊,我的错 - 我没有注意到 dotvvm 标签。
      猜你喜欢
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 2013-02-24
      • 1970-01-01
      相关资源
      最近更新 更多