【发布时间】:2014-01-05 22:38:05
【问题描述】:
我正在开发一个 asp.net mvc 4 Web 应用程序,我编写了以下自定义授权类:-
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CheckUserPermissionsAttribute : AuthorizeAttribute
{
public string Model { get; set; }
public string Action { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.Request.IsAuthenticated)
return false;
//code goes here
if (!repository.can(ADusername, Model, value)) // implement this method based on your tables and logic
{
return false;
//base.HandleUnauthorizedRequest(filterContext);
}
return true;
// base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var viewResult = new JsonResult();
viewResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
viewResult.Data = (new { IsSuccess = "Unauthorized", description = "Sorry, you do not have the required permission to perform this action." });
filterContext.Result = viewResult;
}
else
{
var viewResult = new ViewResult();
viewResult.ViewName = "~/Views/Errors/_Unauthorized.cshtml";
filterContext.Result = viewResult;
}
base.HandleUnauthorizedRequest(filterContext);
}
}
}
但我现在面临的唯一问题是,如果授权失败,则将提示用户输入用户名和密码,尽管我已经覆盖 HandleUnauthorizedRequest 以根据请求是否为 AJAX 返回视图或 JSON .所以你能建议为什么在授权失败时提示用户输入他的用户名和密码,而不是接收 _unauthorized 视图或包含错误消息的 JSON
【问题讨论】:
标签: asp.net asp.net-mvc-4 iis authorize-attribute