我正在开发一个项目,我需要在Session中设置一些值,然后检索它。但问题是它总是返回null。
HomeController.cs
public class HomeController: Controller
{
public HomeController()
{
Connect();
}
public async Task Connect()
{
pbx.WaitingCallsChanged += Changed;
pbx.PhoneCallsChanged += PhoneChanged;
}
public void PhoneChanged(object sender, PhoneChangedEventArgs e)
{
//when this method is triggered set this value to session
Session["all"] = e.Active;
}
private void Changed(object sender, WaitingCallsChangedEventArgs e)
{
//when this method is triggered set this value to session
Session["waiting"] = e.Queue;
}
public ActionResult GetWaiting()
{
//when this method is called with ajax return only current Session values
return Json(new { waiting = Session["waiting"], all = Session["all"] }, 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>
Index.cshtml.cs
<div id='all'></div>
<div id='waiting'></div>
@section scripts{
<script>
$(function () {
function getWait() {
$.ajax({
url: 'http://localhost:50325/Home/GetWaiting',
success: function (data) {
$('#all').text(data.all);
$('#session').text(data.waiting);
}
});
}
setInterval(function () {
getWait();
}, 10);
})
</script>
}
我在这里的确是PhoneChanged和Changed是基于那些pbx.WaitingCallsChanged和pbx.PhoneCallsChaged调用的委托方法。
因此,当调用这两个方法中的一个时,我需要将该值存储在Session上,这样我就可以通过GetWaiting()方法每10毫秒使用ajax“实时”获取它。
P.S。问题可能是因为我做了每个新的ajax调用,它创建了一个新的控制器实例,当创建新实例时,它将Session设置为null?