asp.net mvc Ajax服务器跳转

时间:2022-05-28 17:05:36

1.过滤器权限验证

  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthAttribute : ActionFilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
&& !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
{
UserInfo user = filterContext.HttpContext.Session["CurentUser"] as UserInfo;
if (user == null || user.Id <= )
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new HttpStatusCodeResult();
filterContext.HttpContext.Response.Write("/Home/Login");
return;
}
else
{
filterContext.Result = new RedirectResult("/Home/Login");
return;
}
}
}
}
}

2.客户端重写$.Ajax,最好在母版页中加上此代码,统一处理

 <script type="text/javascript">
(function ($) {
//备份jquery的ajax方法
var _ajax = $.ajax;
//重写jquery的ajax方法
$.ajax = function (opt) {
//备份opt中error和success方法
var fn = {
error: function (XMLHttpRequest, textStatus, errorThrown) { },
}
if (opt.error) {
fn.error = opt.error;
}
//扩展增强处理
var _opt = $.extend(opt, {
error: function (XMLHttpRequest, textStatus, errorThrown) {
//错误方法增强处理
if (XMLHttpRequest.status == "") {
window.location.href = "/FlexibleBenefit/Login";
}
else
{
fn.error(XMLHttpRequest, textStatus, errorThrown);
}
}
});
_ajax(_opt);
};
})(jQuery); $.ajaxSetup({
statusCode: {
: function (data) {
window.location.href = data.responseText;
}
}
});
</script>