在我的控制器C#中设置会话
本文关键字:设置 会话 我的 控制器 | 更新日期: 2023-09-27 18:36:33
我需要在控制器中设置一个会话变量,发现有两种方法可以设置会话,第一个是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";
,这应该有效,但它对我不起作用。我猜我错过了一些配置或其他什么。任何帮助都将不胜感激。提前感谢!
您的控制器确实应该继承自控件。我所做的是能够轻松构建会话,而不会太复杂。我构建了以下内容:
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();
}
}
这是一个简单的例子,但您的类将使用System.Web访问。这将能够正确关联会话。这就是一个例子-
重要信息:为模型视图控制器构建会话时,应谨慎。它是基于无状态的前提。因此,添加会话可能非常难以跟踪,因此您最终可能会遇到流氓会话变量,这可能会导致潜在问题。因此,请确保您的应用程序考虑到了这种潜力,并非常、非常仔细地跟踪它们。
希望这能帮到你。
所以我找到了问题的解决方案。我将展示两个具有正确代码的不同文件,以使System.Web.HttpContext.Current.Session["SessionId"] = "Session Value";
能够工作。这是我的WebApiConfig文件,位于App_Start文件夹:
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总是抛出空指针的问题。