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:
WebSecurty.UserExists , WebSecurity.CreateUserAndAccount . These methods let you determine whether someone is already registered and to register them.
WebSecurty.IsAuthenticated . This property lets you determine whether the current user is logged in. This is useful to redirect users to a login page if they have not already logged in.
WebSecurity.Login , WebSecurity.Logout . These methods log a user in or out.
WebSecurity.CurrentUserName . This property is useful for displaying the current user's logged-in name (if the user is logged in).
WebSecurity.ConfirmAccount . This method is useful if you set up email confirmation for registration. (Details are described in the blog post Using the confirmation feature for ASP.NET Web Pages security.)
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.