Search code examples
javascriptc#asp.net-corerazor

window.onload = function() in `_Layout.cshtml` Infinity loop(ASP.NET Core)


I want to check session in my _layout.cshtml, it can redirect to Login page but it loop infinity

@using Microsoft.AspNetCore.Http
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript">
        window.onload = function () {
            if ('@HttpContextAccessor.HttpContext.Session.GetString("username")' === '') {
                location.href = "@Url.Action("Login", "Account")";
            }
        };
    </script>
</head>
<body>

</body>
</html>

Solution

  • According to your description, I suggest you could write another condition to check if the page is not goes to the account/login. Like below:

    Notice: If you use default identity, the url path should be /Identity/Account/Login, so you should check the request path is it. Besides, I suggest you could directly use location.href = "/Identity/Account/Login" instead of "@Url.Action("Login", "Account")", since it will generate a wrong url if the account controller doesn't contains the login method. This will also cause the Infinity loop.

    <script type="text/javascript">
        window.onload = function () {
        
            if ('@HttpContextAccessor.HttpContext.Session.GetString("username")' === '' && '@HttpContextAccessor.HttpContext.Request.Path' !== '/Identity/Account/Login')
            {
                location.href = "/Identity/Account/Login";
            }
        };
    </script>