简体   繁体   中英

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>

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>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM