2023年6月20日发(作者:)
e中如何通过AuthorizeAttribute做⾃定义验证?咨询区jltrem:我想在 Core 中⽤ authorization 特性实现⼀个⾃定义验证,在之前的版本中,我可以⽤系统提供的 boolAuthorizeCore(HttpContextBase httpContext) ⽅法,但在这个版本中已经没有该⽅法了。请问当前我该如何实现这个⾃定义的 AuthorizeAttribute 呢?回答区gius:看样⼦你⽤的是 Core 2,当然现在你也可以实现,继承 AuthorizeAttribute 并实现 IAuthorizationFilter 接⼝即可,参考代码如下:[AttributeUsage( | , AllowMultiple = true, Inherited = true)]public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter{ private readonly string _someFilterParameter; public CustomAuthorizeAttribute(string someFilterParameter) { _someFilterParameter = someFilterParameter; } public void OnAuthorization(AuthorizationFilterContext context) { var user = ; if (!enticated) { // it isn't needed to set unauthorized result
// as the base class already requires the user to be authenticated // this also makes redirect to a login page work properly // = new UnauthorizedResult(); return; } // you can also use registered services var someService = vice
2023年6月20日发(作者:)
e中如何通过AuthorizeAttribute做⾃定义验证?咨询区jltrem:我想在 Core 中⽤ authorization 特性实现⼀个⾃定义验证,在之前的版本中,我可以⽤系统提供的 boolAuthorizeCore(HttpContextBase httpContext) ⽅法,但在这个版本中已经没有该⽅法了。请问当前我该如何实现这个⾃定义的 AuthorizeAttribute 呢?回答区gius:看样⼦你⽤的是 Core 2,当然现在你也可以实现,继承 AuthorizeAttribute 并实现 IAuthorizationFilter 接⼝即可,参考代码如下:[AttributeUsage( | , AllowMultiple = true, Inherited = true)]public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter{ private readonly string _someFilterParameter; public CustomAuthorizeAttribute(string someFilterParameter) { _someFilterParameter = someFilterParameter; } public void OnAuthorization(AuthorizationFilterContext context) { var user = ; if (!enticated) { // it isn't needed to set unauthorized result
// as the base class already requires the user to be authenticated // this also makes redirect to a login page work properly // = new UnauthorizedResult(); return; } // you can also use registered services var someService = vice
发布评论