在MVC中的控制器通过ajax的方式调用时权限的问题。
只写主要部分
按照错误方式处理
派生AuthorizeAttribute的类方法:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest()) //ajax调用方式
{
filterContext.Result = new ContentResult();
filterContext.HttpContext.Response.StatusCode = Convert.ToInt32(System.Net.HttpStatusCode.Forbidden);
}
else
{
filterContext.Result = new RedirectResult("/Account/LogOff");
}
}
客户端的代码
$.ajax({
type: "GET",
url: "/Test/Test",
async: false,
global: false,
data: {name:"sss"},
cache: false,
success: function (data, textStatus, jqXHR) {
$(outlookbarOpts.workspace).html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 403) { //此处判断StatusCode然后做跳转
window.location.href = "/Account/LogOff";
} else {
$(outlookbarOpts.workspace).html(jqXHR.responseText);
}
}
});
按照成功方式处理
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest()) //ajax调用方式
{
filterContext.Result = new JsonResult
{
Data = new { },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
filterContext.Result = new RedirectResult("/Account/LogOff");
}
}
客户端的代码
$.ajax({
type: "GET",
url: "/Test/Test",
async: false,
global: false,
data: {name:"sss"},
cache: false,
success: function (data, textStatus, jqXHR) {
//在上面的Data中添加一个属性然后在此判断data的属性是否定义然后做出不同的处理方式跳转或者显示
});