asp.net之授权失败时如何返回自定义 View 或 JSON,而不是显示用户名和密码对话框
我正在开发一个 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 返回 View 或 JSON .所以你能建议为什么当授权失败时提示用户输入他的用户名和密码,而不是接收 _unauthorized View 或包含错误消息的 JSON
请您参考如下方法:
but the only problem i am facing now is that if the authorization fail then the user will be prompted to enter username and password, although i have override the HandleUnauthorizedRequest to return a view or JSON based on if the request is AJAX or not.
那是因为您绝对总是在 HandleUnauthorizedRequest 方法中点击以下行:
base.HandleUnauthorizedRequest(filterContext);
你知道这条线是做什么的吗?它调用基本方法。你知道基本方法是做什么的吗?它返回 401 状态代码。您知道在使用表单例份验证的 ASP.NET 应用程序中返回 401 状态响应代码时会发生什么吗?您将获得登录页面。
是的,如果您正在使用 AJAX 或其他东西并打算返回一些 JSON 或其他东西,请确保永远不会调用基本内容。顺便说一下,在您的 else 条件下,您似乎正在尝试呈现一些 ~/Views/Errors/_Unauthorized.cshtml View ,这显然再次无用,因为您也在调用将简单地重定向到登录页面的基本方法。
我认为在我回答的这个阶段,您已经知道该怎么做:摆脱 HandleUnauthorizedRequest 方法的最后一行,在该方法中,您通过调用基本方法。
如果您想正确地做事并返回 401 状态代码而不是获取登录页面而是返回一些自定义 JSON,您可以使用 SuppressFormsAuthenticationRedirect Response 对象的属性。如果您使用的是一些没有此属性的 .NET 框架的旧版本,您可能会发现 following blog post Phil Haack 在其中解释了如何处理这种情况很有用。
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。



