gpt4 book ai didi

c# - ASP.NET IAuthorizationFilter OnAuthorization

转载 作者:可可西里 更新时间:2023-11-01 07:55:55 26 4
gpt4 key购买 nike

您好,我正在尝试实现自定义授权过滤器

 //The Authourization attribute on a controller
public class CustomAdminAuthorizationFilter : IAuthorizationFilter
{
private readonly IAuthentication _authentication;

public SageAdminAuthorizationFilter(IAuthentication authentication)
{
_authentication = authentication;
}

public void OnAuthorization(AuthorizationContext filterContext)
{
bool result = _authentication.Authorize(filterContext.HttpContext);
}
}

正如您在 OnAuthorization 上看到的那样,我得到了一个真假的结果。我需要设置什么才能返回我来自的地方?

编辑:

它似乎仍然直接把我扔到登录页面

我确实注入(inject)了 IAuthetication

 this.BindFilter<CustomAdminAuthorizationFilter>(FilterScope.Controller, 0);
Bind<IAuthentication>().To<CustomAuthenticationService>();

然后我在 Controller 中装饰我的 Action 。

[Authorize]
public ActionResult Index()
{
ViewBag.Title = "Welcome";
ViewBag.Message = "Welcome to ASP.NET MVC!";

return View();
}

在我的 web.config 中我正在使用

<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>

这应该改变吗?

如有任何帮助,我们将不胜感激。

最佳答案

将其更改为 Attribute,而不是简单的 IAuthorizationFilter

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class SageAdminAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
readonly IAuthentication _authentication;

public SageAdminAuthorizeAttribute(IAuthentication authentication)
{
_authentication = authentication;
}

public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!_authentication.Authorize(filterContext.HttpContext))
filterContext.Result = new HttpUnauthorizedResult();
}
}

现在不要使用 [Authorize],而是使用新的 [SageAdminAuthorize] 属性

[SageAdminAuthorize]
public ActionResult Index()
{
ViewBag.Title = "Welcome";
ViewBag.Message = "Welcome to ASP.NET MVC!";

return View();
}

关于c# - ASP.NET IAuthorizationFilter OnAuthorization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5663405/

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