Request.IsAuthenticated总是错误的

Kma*_*zek 26 c# asp.net-mvc

你能告诉我为什么FormsAuthentication.SetAuthCookie(user.Name, false);不是Request.IsAuthenticated真的吗?

这是我的代码:

[HttpPost]
    public ActionResult LogIn(karcioszki.Models.UserLoginModel  user)
    {
        if (ModelState.IsValid)
        {
            if (IsValid(user.Name, user.Password))
            {
                FormsAuthentication.SetAuthCookie(user.Name, false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Login or password is incorrect");
            }
        }

        return View(user);
    }
Run Code Online (Sandbox Code Playgroud)

如果声明:

@if (Request.IsAuthenticated)
{
    <a href="@Href("~/")" class="active">Home</a>
    <a href="@Href("~/Cards")">Cards</a>
    @Html.ActionLink("Log out", "Logout", "User")
    @Html.Encode(User.Identity.Name)
}
Run Code Online (Sandbox Code Playgroud)

另外,请告诉我,如何使它工作?

编辑:我在web.config(两者)中添加了身份验证,但它仍然无法正常工作.

<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Windows"/>
<pages>
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
    <add namespace="System.Web.Optimization" /> 
  </namespaces>
</pages>
Run Code Online (Sandbox Code Playgroud)

我应该使用Windows还是其他模式?

小智 47

我在MVC5项目中遇到了同样的问题.解决方案是将以下行添加到system.webServer中的modules部分

<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
Run Code Online (Sandbox Code Playgroud)


小智 16

您必须FormsAuthentication.SetAuthCookie(acct.UserName, true); 在验证用户后进行设置,并且请检查您是否必须authentication mode="Forms"在web.config中进行设置.


Lon*_*ong 9

在Web.config中添加以下代码

<authentication mode="Forms">
  <forms loginUrl="~/_Login/Login" timeout="30" />
</authentication>
Run Code Online (Sandbox Code Playgroud)

  <modules>
  <remove name="FormsAuthentication" />
  <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
</modules>
Run Code Online (Sandbox Code Playgroud)