【发布时间】:2022-01-17 21:19:05
【问题描述】:
定义问题
我发现在 ASP.NET MVC 应用程序中设置会话持续时间有两种方法:
- 在
web.config文件的<sessionState>字段中为timeout属性设置一个值。 - 在
Global.asax.cs文件中的Session_Start()方法中设置Session.Timeout属性。
当web.config文件如下实现时,第一种方法不起作用,如the document中提到的,我得到HTTP 404错误:
<configuration>
<system.web>
<sessionState mode="InProc" cookieless="true" timeout="60" />
</system.web>
</configuration>
但是,第二种方法在Global.asax.cs 文件中实现时有效,如下所示:
public class ApplicationName : System.Web.HttpApplication
{
protected void Session_Start(object sender, EventArgs e)
{
/* Sets the session duration to 60 minutes. */
Session.Timeout = 60;
}
}
错误代码通知
当我使用第一种方法时,单击/Login/Index 页面上的“登录” 按钮时出现HTTP 404 错误。因为虽然输入了正确的用户名和密码,但是页面被重定向到/{token}/Login/LoginControl页面,而页面应该被重定向到/Profile页面。我不知道这种行为是如何发生的。
相关源码
LoginController.cs文件中的相关方法和Login/Index.cshtml文件中定义的脚本如下:
public class LoginController : PublicController
{
private readonly IUserService _userService;
private readonly IUnitOfWork _uow;
private SessionContext _sessionContext;
public LoginController(IUnitOfWork uow, IUserService userService) : base(uow)
{
_uow = uow;
_userService = userService;
_sessionContext = new SessionContext();
}
[HttpPost]
public ActionResult LoginControl(ELoginDTO login)
{
var result = _userService.GetUserByUserName(login.UserName, login.Password);
if (result != null)
{
AutoMapper.Mapper.DynamicMap(result, _sessionContext);
Session["SessionContext"] = _sessionContext;
return Json("/Profile", JsonRequestBehavior.AllowGet);
}
else
{
return Json("", JsonRequestBehavior.AllowGet);
}
}
}
点击“LOGIN”按钮触发FUNCTION_LoginControl()脚本:
function FUNCTION_LoginControl()
{
var model = { UserName: $("#inputUserName").val(), Password: $("#inputPassword").val() };
if (model.UserName.trim() != "" && model.Password.trim() != "")
{
$.ajax({
url: "/Login/LoginControl",
type: "POST",
data: model,
success: function (e) {
if (e != "")
{
window.location = e;
}
}
});
}
}
【问题讨论】:
标签: c# asp.net asp.net-mvc session asp.net-ajax