asp.net-mvc - 当用户没有权限时如何重定向到特殊页面?
问题描述
我注册了一个用户,然后为它设置了无效。当用户填写表格时,我想激活用户。
await _userManager.AddClaimAsync(user.Id,new Claim("DeActive", "1"));
注册后将用户重定向到管理区域,我想将用户重定向到每个链接菜单中的特殊页面,直到用户填写特殊表格。
如何为该区域的所有控制器操作设置重定向页面?
解决方案
public class MyAuthorizeAttribute: AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not authorized => no need to go any further
return false;
}
// We have an authenticated user, let's get his username
string authenticatedUser = httpContext.User.Identity.Name;
// and check if he has completed his profile
if (!this.IsProfileCompleted(authenticatedUser))
{
// we store some key into the current HttpContext so that
// the HandleUnauthorizedRequest method would know whether it
// should redirect to the Login or CompleteProfile page
httpContext.Items["redirectToCompleteProfile"] = true;
return false;
}
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Items.Contains("redirectToCompleteProfile"))
{
var routeValues = new RouteValueDictionary(new
{
controller = "someController",
action = "someAction",
});
filterContext.Result = new RedirectToRouteResult(routeValues);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
private bool IsProfileCompleted(string user)
{
// You know what to do here => go hit your database to verify if the
// current user has already completed his profile by checking
// the corresponding field
throw new NotImplementedException();
}
}
推荐阅读
- c++ - 如何查看 .i 文件中的源代码?
- spring - @JsonFormat 日期字段到本地时区
- java - 添加到另一个类中的数组?
- http - chai-http 并不总是看到 ETag 标头,可能是由于 CORS?
- excel - Copy from textbox to cell and maintain all formatting with vba
- javascript - Jquery中的预加载器
- python - Python 的 json 负载仍然占用大量内存?
- java - 为什么我的代码在 for 循环之后没有执行?
- firebase - 注销时取消订阅 Firestore 侦听器
- javascript - Angular:无法读取未定义的属性“id”