【问题标题】:Set Session in my Controller C#在我的控制器 C# 中设置会话
【发布时间】:2015-01-06 20:42:31
【问题描述】:

我需要在控制器中设置一个会话变量,发现设置会话有两种方式, 第一个是Session["SessionId"] = "Session Value"; 第二个是System.Web.HttpContext.Current.Session["SessionId"] = "Session Value"; 使用第一种方式时,我必须继承: System.Web.HttpApplication。 所以我的控制器看起来像这样 ->

public class LoginControllerWithSession : System.Web.HttpApplication
{        
    public Boolean userLoginSetSession(string username)
    {
        Session["username"] = username;
    }
}

我的 web.config 看起来像这样 ->

<system.web>
    <sessionState mode="InProc">
        <providers>
            <remove name="Session" />
            <add name="Session" type="System.Web.SessionState.SessionStateModule"
            preCondition="" />       
        </providers>
    </sessionState>
</system.web>

所以我遇到的问题是当Session["username"] = username; 运行时会引发异常:Session state is not available in this context.,如果我使用System.Web.HttpContext.Current.Session 的其他方式,它将引发空指针异常。我不明白我错过了什么。我发现的所有研究都说只使用第一种方法:Session["SessionId"] = "Session Value"; 这应该可以工作,但它对我不起作用。我猜我缺少一些配置或其他什么。任何帮助将不胜感激。提前致谢!

【问题讨论】:

  • 为什么你的控制器继承自 System.Web.HttpApplication 而不是 Controller?

标签: c# asp.net session controller web-config


【解决方案1】:

您的 Controller 确实应该从 Controller 继承。我所做的就是能够轻松地构建一个 Session,而没有太多的复杂性。我构建了以下内容:

public class Storage
{
     public void SessionAdd(string label, string content)
     {
         if(string.IsNullOrEmpty(label) || string.IsNullOrEmpty(content))
              return;

         HttpContext.Current.Session.Add(label, content);
     }

     public void SessionPurge()
     {
         var context = HttpContext.Current;
         if(context.Session != null)
              context.Session.Clear();
     }
}

这是一个简单的例子,但是您的 Class 将拥有 访问 以 使用 System.Web。这将能够正确关联 Session。这是一个例子-

重要提示:当您为 Model View Controller 构建 Session 时,您应该谨慎。它是以无状态为前提的。因此,添加 Session 可能难以跟踪,因此您最终可能会得到 rogue Session Variables,这可能会导致潜在问题。因此,请确保您的应用程序考虑到了这种潜力,并且非常非常仔细地跟踪它们。

希望这对您有所帮助。

【讨论】:

  • 当应用程序遇到 HttpContext.Current.Session 时,它会中断并抛出空指针异常。我在 global.asax 中找到了一些我猜是丢失的代码;它是 session_start(Object sender, EventArgs e) 但我仍然不确定如何使用它。感谢您的回复。
  • 我必须看看你的代码,但你应该可以从你的控制器调用它:(new Storage()).SessionAdd("Example", example);。
  • 可以调用 SessionAdd 方法,但是当应用程序点击 HttpContext.Current.Session 时,它会抛出一个空指针。
  • 添加还是清除?如果您在添加时收到 null,则它没有正确地从应该包含 HttpContext 的 System.Web 中提取,或者您的服务器不允许存储 Session。我需要看看你的代码。
  • 我找到了解决方案。我在 global.asax Application_PostAuthorizeRequest 中缺少一个方法。现在,当我调用 HttpContext.Current.Session 时,它不会抛出空指针。
【解决方案2】:

所以我找到了解决问题的方法。我将使用正确的代码展示两个不同的文件,以使System.Web.HttpContext.Current.Session["SessionId"] = "Session Value"; 能够工作。 这是位于 App_Start 文件夹中的 WebApiConfig 文件:

public static class WebApiConfig
{

    public static string UrlPrefix { get { return "api"; } }
    public static string UrlPrefixRelative { get { return "~/api"; } }

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

这是 Global.asax 文件:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // starter code here
    }

    protected void Application_PostAuthorizeRequest()
    {
        if (IsWebApiRequest())
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    }

    private bool IsWebApiRequest()
    {
        return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
    }
}

Application_PostAuthorizeRequest 和 IsWebApiRequest 对于使用HttpContext.Current 是必不可少的。如果 global.asax 中没有这些方法,您的 HttpContext.Current.Session 将始终因空指针异常而中断。 我希望这可以帮助任何遇到我在 Session 总是抛出空指针的地方遇到同样问题的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多