How to return 401 instead of 302 in ASP.NET Core?

后端 未结 8 2095
迷失自我
迷失自我 2020-11-29 03:36

I\'m trying to get ASP.NET Core Identity to return 401 when a user isn\'t logged in. I\'ve added an [Authorize] attribute to my method and instead of returning

8条回答
  •  时光说笑
    2020-11-29 04:11

    If the request header contains X-Requested-With: XMLHttpRequest the status code will be 401 instead of 302

    private static bool IsAjaxRequest(HttpRequest request)
        {
            return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
                string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal);
        }
    

    See on gitHub: https://github.com/aspnet/Security/blob/5de25bb11cfb2bf60d05ea2be36e80d86b38d18b/src/Microsoft.AspNetCore.Authentication.Cookies/Events/CookieAuthenticationEvents.cs#L40-L52

提交回复
热议问题