asp.net-mvc-4 – ASP.NET MVC 4自定义权限属性 – 如何将未经授
发布时间:2020-12-16 00:37:18 所属栏目:asp.Net 来源:网络整理
导读:参见英文答案 ASP.NET MVC – How to show unauthorized error on login page?7个答案我正在使用自定义授权属性来授权用户根据权限级别进行访问。我需要重定向未经授权的用户(例如,用户尝试删除没有删除访问级别的发票)来访问被拒绝的页面。 自定义属性正在
参见英文答案 >
ASP.NET MVC – How to show unauthorized error on login page?7个答案我正在使用自定义授权属性来授权用户根据权限级别进行访问。我需要重定向未经授权的用户(例如,用户尝试删除没有删除访问级别的发票)来访问被拒绝的页面。
自定义属性正在工作。但是在未经授权的用户访问的情况下,浏览器中没有显示任何内容。 Contoller代码。 public class InvoiceController : Controller { [AuthorizeUser(AccessLevel = "Create")] public ActionResult CreateNewInvoice() { //... return View(); } [AuthorizeUser(AccessLevel = "Delete")] public ActionResult DeleteInvoice(...) { //... return View(); } // more codes/ methods etc. } 自定义属性类代码。 public class AuthorizeUserAttribute : AuthorizeAttribute { // Custom property public string AccessLevel { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) { return false; } string privilegeLevels = string.Join("",GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB if (privilegeLevels.Contains(this.AccessLevel)) { return true; } else { return false; } } } 感谢您能分享您的经验。 解决方法
您必须按照
here规定覆盖HandleUnauthorizedRequest。
public class CustomAuthorize: AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if(!filterContext.HttpContext.User.Identity.IsAuthenticated) { base.HandleUnauthorizedRequest(filterContext); } else { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new{ controller = "Error",action = "AccessDenied" })); } } } **注意:更新的条件语句Jan ’16 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- asp.net – 自定义动态数据中的数据注释
- asp.net-mvc – 无法加载文件或程序集”或其依赖
- asp.net – 如何创建google网站地图mvc网站?
- asp.net – 在代码中获取页面的绝对URL
- .net – 实体框架遇到的最大池大小4.3
- asp.net-mvc – 在MVC Web应用程序中的存储库中共
- asp.net – Global.asax.cs事件在网站发布后未触
- asp.net-mvc-5 – 当EnableOptimizations为true时
- asp.net – 有没有办法在Web Api控制器中处理表单
- asp.net-mvc – ASP.NET Core中基于活动的授权
热点阅读