呼叫从一个控制器到另一个方法,当会话为null ... MVC [英] Session is null when calling method from one controller to another...MVC

查看:167
本文介绍了呼叫从一个控制器到另一个方法,当会话为null ... MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC应用程序,我增加了一个新的控制器,并从现有的控制器调用这一新控制器的方法。我使用的会话变量,并在控制器A我调用该方法在控制器B:

I have an ASP.NET MVC app and i added a new controller to it and call a method from this new controller from an existing controller. I am using session variables and in controller A i call the method in controller B:

if (Session["Grid"] != null){}//session object is fine here
      ControllerB b  = new ControllerB ();
b.CallMethod();

在新的控制器,我打电话B,方法如下:

In the new controller, which i'm calling B, the method looks like this:

public object CallMethod(){
    if (Session["Grid"] != null)//session object is null
        {
            //do my thing
        }
  }

会话变量心不是问题,它的会话对象。它完全空的,因此我的应用程序炸毁。这次会议是生命力,在控制器A,那么,为什么在空控制器B?谢谢

The session variable isnt the problem, its the session object. Its completely null, hence my application blows up. The session is alive and well in controller A, so why is it null in controller B? Thank you

推荐答案

这是因为 ControllerB 需要初始化自身,并作为这个过程还设置的一部分会话请求 Resposne 等相应。

That's because ControllerB needs to initializes itself, and as part of this process it also sets Session, Request, Resposne etc accordingly.

所以,你需要调用初始化方法,并通过它的电流的RequestContext 。但是,因为它被标记为保护(因为它注定不会被直接调用,只能使用的ControllerFactory ) ,你必须将其暴露:

So, you need to call the Initialize method and pass it the current RequestContext. But, since it's marked as protected (because it wasn't meant to be called directly, only using the ControllerFactory), you'll have to expose it:

public class ControllerB : Controller
{
    public void InitializeController(RequestContext context)
    {
        base.Initialize(context);
    }
}



ControllerA <然后/ code>:

Then in your ControllerA:

var controllerB = new ControllerB();
controllerB.InitializeController(this.Request.RequestContext);



另外,因为会话吸气实际上是为 this.ControllerContext.HttpContext.Session 的简写(同为请求响应等),您可以设置 ControllerContext 而不是:

Alternatively, since the Session getter is actually a shorthand for this.ControllerContext.HttpContext.Session (same for Request, Response etc), you can set the ControllerContext instead:

var controllerB = new ControllerB();
controllerB.ControllerContext = new ControllerContext(this.Request.RequestContext, controllerB);

请参阅的 MSDN

这篇关于呼叫从一个控制器到另一个方法,当会话为null ... MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆