ASP.NET MVC项目Forms身份验证HttpContext.Current.User为空

Forms 身份验证采用FormsAuthentication类,本地开发环境运行正常,当部署到测试环境上HttpContext.Current.User总是为空。

例如

登录代码

[HttpPost]
public ActionResult LogOn(LogOnModel model)
{
  if (ModelState.IsValid)
  {

    if (model.UserName == "username" && model.Password == "password")
    {
      FormsAuthentication.RedirectFromLoginPage(model.UserName, model.RememberMe);
    }
  }

  return View("logon failed!");
}

退出代码

public ActionResult LogOff()
{
     //FormsService.SignOut();
     FormsAuthentication.SignOut();

     return RedirectToAction("Index", "Home");
}

web.config设置

< system.web >
       < authentication mode = "Forms" >
          <forms loginUrl = "~/Account/Login" timeout = "2" />
      </ authentication >
</ system.web >

部署到测试环境上HttpContext.Current.User总是为空,解决办法,IIS集成模式下,默认所加载模块并不是完全加载了FormsAuthentication模块,需要我们手动重新加载该模块。

<system.webServer>
   ...
    <modules>
     ...
      <remove name="FormsAuthentication" /> 
      <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" /> 
    </modules>
  </system.webServer>

官方文档参考:https://docs.microsoft.com/en-us/iis/application-frameworks/building-and-running-aspnet-applications/aspnet-integration-with-iis#enabling-aspnet-services-for-all-types-of-content

为什么不能完全加载?而需要手动重新加载呢?读懂官方文档的大侠,还望告知。

原文地址:https://www.cnblogs.com/songshuai/p/11251869.html