gpt4 book ai didi

c# - ASP.NET MVC 5 处理未经授权的请求

转载 作者:行者123 更新时间:2023-11-30 17:46:12 25 4
gpt4 key购买 nike

我正在尝试在具有个人用户帐户身份验证模式的新 ASP.NET MVC 5 项目上实现拒绝访问错误页面。我添加继承自 AuthorizeAttribute

CustomAuthorize
public class CustomAuthorize : AuthorizeAttribute
{
protected virtual CustomPrincipal CurrentUser
{
get { return HttpContext.Current.User as CustomPrincipal; }
}

public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
if (!string.IsNullOrEmpty(Roles))
{
if (!CurrentUser.IsInRole(Roles))
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));

//base.OnAuthorization(filterContext); // returns to login url
}
}

if (!string.IsNullOrEmpty(Users))
{
if (!Users.Contains(CurrentUser.UserName))
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));

//base.OnAuthorization(filterContext); // returns to login url
}
}
}
}


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" }));
}
}
}

添加ErrorController.cs

public class ErrorController : Controller
{
public ActionResult AccessDenied()
{
return View();
}
}

AccessDenied.cshtml查看

<h2>Access Denied</h2>
<p>You do not have access to view this page</p>

然后应用到HomeController.cs

[CustomAuthorize]
public class HomeController : Controller

但它总是重定向到登录页面。如何显示访问被拒绝的页面?

最佳答案

使用个人用户帐户创建新的 mvc 5 项目,添加错误 Controller 、 View 和 CustomAuthorize 属性类。

然后像下面这样更新家庭 Controller 。

public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}

[CustomAuthorize(Roles = "TestRole")]
public ActionResult About()
{
ViewBag.Message = "Your application description page.";

return View();
}

public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";

return View();
}
}

注册并登录,尝试点击“关于”链接,您将被重定向到访问被拒绝的页面,因为没有角色为“TestRole”的用户

关于c# - ASP.NET MVC 5 处理未经授权的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26487979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com