将 Application_EndRequest 处理程序添加到 global.asax.cs 中的代码,将任何 302 错误(重定向到登录页面)修改为 AJAX 请求的 401(未经授权)错误。这将允许您简单地将控制器操作保持原样并通过客户端处理重定向(如果当前没有,您实际上只能让用户再次登录)。
protected void Application_EndRequest()
{
// Any AJAX request that ends in a redirect should get mapped to an unauthorized request
// since it should only happen when the request is not authorized and gets automatically
// redirected to the login page.
var context = new HttpContextWrapper( Context );
if (context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
{
context.Response.Clear();
Context.Response.StatusCode = 401;
}
}
然后在您的 _Layout.cshtml 文件中添加一个全局 AJAX 错误处理程序,该处理程序在收到 401 响应时重定向到您的登录操作。
<script type="text/javascript">
$(function () {
$(document).ajaxError(function (e, xhr, settings) {
if (xhr.status == 401) {
location = '@Url.Action( "login", "account" )';
}
});
});
</script>
您可能还想尝试 Phil Haack 的博客中概述的一些技术,当您不想使用时防止表单身份验证登录页面重定向