MaxK123
MaxK123

Reputation: 450

Make a logout button in ASP.NET Core

I am new to ASP.NET Core and I have made a login page with simple authentication via a session. I am trying to make a button that will log you out, but I cannot figure out how to do it. This is what Ive come up with:

This is my controller:

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        IConfiguration _Configuration;
        SecurityService _securityService;

        public HomeController(ILogger<HomeController> logger,
            IConfiguration configuration,
            SecurityService securityService)
        {
            _logger = logger;
            _Configuration = configuration;
            _securityService = securityService;
        }

        public IActionResult Index()
        {
            var loggedIn = HttpContext.Session.GetString("SessionUser");
            if(loggedIn == "admin")
            {
                return View();
            }
            else
            {
                return View("Login");
            }
        }

        public IActionResult Login(UserModel user)
        {
            Boolean success = _securityService.Authenticate(user, _Configuration);
            

            if (success)
            {
                HttpContext.Session.SetString("SessionUser", user.Username);
                return RedirectToAction("Index");
            }
            else
            {
                return View("Login");
            }
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }

Here is my SecurityDAO where I look for if the user exists in the database:

public class SecurityDAO
    {
        internal bool FindByUser(UserModel user, IConfiguration Configuration)
        {
            string connectionString = Configuration["ConnectionStrings:Database"];
            bool success = false;

            string queryString = "SELECT * FROM users WHERE username = @username AND password = @password";

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand command = new MySqlCommand(queryString, connection);

                command.Parameters.Add("@username", MySqlDbType.VarChar, 50).Value = user.Username;
                command.Parameters.Add("@password", MySqlDbType.VarChar, 50).Value = user.Password;

                try
                {
                    connection.Open();
                    MySqlDataReader reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        success = true;
                    }
                    else
                    {
                        success = false;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return success;
        }
    }

Here is my SecurityService:

public class SecurityService
    {
        SecurityDAO daoService = new SecurityDAO();

        public bool Authenticate(UserModel user, IConfiguration Configuration)
        {
            return daoService.FindByUser(user, Configuration);
        }
    }

Thanks beforehand! Best regards Max

Upvotes: 1

Views: 3764

Answers (1)

coolhand
coolhand

Reputation: 2061

You can create an anchor element to your View and use an asp-action tag to call the appropriate action method in your controller:

<a class="btn" asp-action="Logout" asp-controller="Home">Logout</a>

If you want to hide this button when a user is logged in you can pass a model string to the View within your controller and determine whether to show the button using your SessionUser data

@if(!string.IsNullOrEmpty(Model.SessionUser))
{
    <a class="btn" asp-action="Logout" asp-controller="Home">Logout</a>
}

Upvotes: 1

Related Questions