Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

c# - Request.IsAuthenticated is always false

Can you tell me why FormsAuthentication.SetAuthCookie(user.Name, false); is not causing Request.IsAuthenticated to be true?

Here is my code:

[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);
    }

and if statement:

@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)
}

Also, please tell me, how to make it work?

EDIT: I added authentication in web.config(both) but it still isn't working.

<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>

Should I use Windows or other mode?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same problem in an MVC5 project. The solution was to add the following lines to the modules section in the system.webServer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...