asp.net-mvc-4 – ASP.NET MVC 4自定义权限属性 – 如何将未经授权的用户重定向到错误页面?
发布时间:2020-05-23 16:27:15 所属栏目: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中防止SQL注入
- asp.net-mvc – ASP.NET MVC ViewModel方法 – 是“合法”吗
- asp.net-mvc – Ninject.MVC3,Nuget,WebActivator哦我的
- asp.net-mvc-3 – 基于字符串创建ViewBag属性
- asp.net-mvc-3 – 如何使用MiniProfiler与单页Web应用程序/
- ef-code-first – ASP.NET Identity – 将用户ID主键默认类
- asp.net-mvc – 如何从FilterAttribute中获取当前的Url?
- asp.net – 您如何看待Postgres和Firebird数据库?
- 从ASP.Net中的sessionID获取会话对象
- 在ASP.NET应用程序中使用Ajax更新面板的优点和缺点
推荐文章
站长推荐
- asp.net – 导致GridView无效回发的TemplateFiel
- asp.net-mvc – 属性似乎根本不起作用
- asp.net-mvc – 在MVC命令,优先级和功能问题中授
- asp.net-mvc – 仅当不使用角色时,如何重定向[Au
- asp.net-mvc – 如何阻止用户在MVC3应用程序上登
- 结帐后asp.net – “无效的标记’,’在类,结构或
- asp.net-web-api – 如何在StructureMap Service
- 在Asp.net Web API中捕获404错误
- asp.net – 存储库模式最佳实践
- asp.net – 什么是Thread.CurrentPrincipal,它有
热点阅读
