Login in ASP c#

Jack Herer 110 Reputation points
2023-04-26T18:12:02.0033333+00:00

Hey lads, here's how to implement login in asp c#... Hope you find it useful.

    public class LoginController : Controller
    {
        public MyContext Context = new MyContext();

        // parameters are nullable, because user does not have to post them
        public IActionResult Index(string? name, string? password)
        {            
            // setting user object for the one, that checks with name, that user posts
            User user = myContext.users.Where(u => u.name == name).FirstOrDefault();
            
            // if that user doesnt exists, or the password is wrong, user is redirected to login page
            if (uzivatel == null || uzivatel.heslo != heslo)
            {
                return View("/Views/Login.cshtml");
            }
            
            // if username and password matches user's login credencials, new session object is created 
            HttpContext.Session.SetString("login", user.name);

            // user is then redirected to his homepage
            return RedirectToAction("Index", "UserHomePage");
        }
    }
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,563 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,197 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.