How to log in using ASP.NET MVC4?

Here are some code snippets from my attempt. This does not work; after "logging in" the user is not redirected to the home page / index, but the login page simply 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> 
+4
source share
2 answers

Are you using ASP.NET MVC 4 Internet Template? if not, I suggest you create a new ASP.NET MVC project using the Internet template, open the account controller and see the methods.

Since @ user1 correctly said one way to do this, use

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

But, as you say, you are using ASP.NET MVC 4. You must use the WebSecurity class .

For instance:

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

Further reading:

+11
source

I suspect you are not setting a cookie to authenticate forms, so the redirect does not work. Ideally, in your login method, you will verify the username and password using some sort of logic, and when you are satisfied that the user is legitimate, you should set the forms authentication cookie and then redirect the user

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

If you do not set up an authentication cookie, the redirect will not work, as the request will still be considered as an unauthenticated request, and the user will be sent back to the login page. You can find more information about forms here.

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

+2
source

Source: https://habr.com/ru/post/1444221/


All Articles