【发布时间】:2018-05-17 16:16:17
【问题描述】:
我正在做一个关于 ASP.NET MVC 的项目,我需要使用 Session 来存储一些数据。
这是代码:
HomeController.cs
public class HomeController : Controller
{
public HomeController()
{
}
public void ChangeValue(){
//I get userId with some other data from db and set to session
//but for the sake of simplicity i set here to 10.
Session["getSession"] = "10";
}
//I use this method only for getting the changed session value
public ActionResult GetWaiting()
{
//now i just need to return the changed value
return Json(Session["getSession"], JsonRequestBehavior.AllowGet);
}
}
Web.config
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
<sessionState mode="InProc" timeout="1" cookieless="true" />
</system.web>
索引.cshtml
<h1 id="session"></h1>
@section scripts{
<script>
$(function () {
function getWait() {
$.ajax({
url: 'http://localhost:50325/Home/GetWaiting',
success: function (data) {
$('#session').text('@Session["getSession"]');
}
});
}
setInterval(function () {
getWait();
}, 1000);
})
</script>
}
但问题是每次我尝试从该会话中获取数据时,它都会返回 null(就像我从未使用过它一样)。 我也尝试使用 System.Web.HttpContext.Current.Session["getSession"] 设置 Session 但仍然相同,它没有进行任何更改。 我还尝试更改超时并从 Web.config 中删除 cookieless,但仍然相同。
附言我需要将该值存储到 Session,因为该值正在被另一种方法更改,我只需要检索已由另一种方法设置的新值。
【问题讨论】:
-
@Session["getSession"]在您的脚本中是剃须刀代码 - 在您查看之前在服务器上评估它被发送到浏览器。它不会因为某些服务器端代码更改它而“神奇地”更新。您需要将更新后的值发送回客户端 -
public ActionResult GetWaiting()方法应该在HomeController()类块内,它应该继承 mvc 的Controller类。会话应在您的操作方法中设置。您的代码中有一些错字。 -
@StephenMuecke 刚刚更新了我的问题,如果可以的话,快看看吧。
-
@stom 刚刚更新了我的问题,如果可以的话,快看看吧。
-
您不能只是完全更改您的问题并使需要添加的 cmets 和答案无效(我已回滚您的更改)。如果您想添加您尝试过的其他代码,请将其附加到您的原始问题
标签: asp.net asp.net-mvc asp.net-mvc-4 session