Evg*_*vin 18 asp.net-mvc jquery unauthorized http-status-code-401 asp.net-mvc-3
我有许多ajax动作的应用程序(使用JQuery.ajax实现),它返回JSON ot html.其中一些应该只有授权用户才能访问,我用[Authorize]
属性修饰它们.对于非ajax操作,如果用户未被授权 - 系统将其重定向到登录页面(在web.config中配置).
但是这不适用于ajax操作,因为如果用户被授权 - 他加载页面,在cookie过期后他没有被授权,而不是html块,它应该替换旧的,他在块内得到我的登录页面.
我知道我可以手动解决这个问题,例如删除[Authorize]属性,如果用户没有授权,则返回特殊的json/empty html.但我不喜欢这个解决方案,因为我需要重写我的所有动作和ajax函数.我想要全局解决方案,允许我不要重写我的操作(可能是自定义授权属性,或某些http未经授权的结果自定义处理).
我想返回状态代码,如果请求是ajax,并且重定向到登录页面,如果请求不是ajax.
tva*_*son 32
将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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在_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>
Run Code Online (Sandbox Code Playgroud)
您可能还想尝试一下Phil Haack博客中概述的一些技术,当您不想要它时,阻止表单身份验证登录页面重定向
归档时间: |
|
查看次数: |
13096 次 |
最近记录: |