简体   繁体   中英

How to login using ASP.NET MVC4?

Here are some bits of code from my attempt. It does not work; after "logging in", the user isn't redirected to the home/index page, but the login page just reloads.

Web.config:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" />
</authentication>

...

<defaultDocument>
  <files>
    <add value="~/Account/Login"/>
  </files>
</defaultDocument>

Controllers/AccountController.cs:

public class AccountController : Controller
{
    //
    // GET: /Account/Login
    public ActionResult Login()
    {
        return View();
    }
}

Views/Account/Login.aspx:

<asp:Login ID="login" runat="server" DestinationPageUrl="~/Views/Home/Index.aspx">
    ...
</asp:Login>

Are you using the internet template of ASP.NET MVC 4 ? if not I suggest you create a new ASP.NET MVC project with internet template, open the Account Controller and have a look and the methods.

As @user1 has rightly said one of the way you could do this is using

 FormsAuthentication.SetAuthCookie(username, true);
 return Redirect(returnurl);

But as you say, you are using ASP.NET MVC 4. You should use WebSecurity Class.

For example :

WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");

Most of the work is done using the following methods and properties of the WebSecurity helper:

Further Reading :

I suspect you are not setting the forms authentication cookie which is why the the redirect is not working. Ideally, in your login method, you will verify the username and password using some logic and when you are satisfied that the user is legit, you have to set the forms authentication cookie and then redirect the user

FormsAuthentication.SetAuthCookie(username, true);
return Redirect(returnurl);

If you don't set the authentication cookie, the redirect will not work since the request will still be treated as an unauthenticated request and the user will be sent back to the login page. You can find more information on forms login here

http://msdn.microsoft.com/en-us/library/xdt4thhy%28v=vs.71%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM