ASP.NETCore中的自定义授权属性我在做asp.netcore,有些东西不太懂。例如,在mvc.net5中,我们可以使用AuthorizeAttribute中的创建类来过滤和授权操作,并将属性设置为如下所示:过滤器上下文);if(filterContext.ResultisHttpUnauthorizedResult)filterContext.Result=newRedirectResult("/Admin/Account/Login");但是在asp.netcore中我们没有AuthorizeAttribute...如何在asp.netcore中为自己定义操作来设置这样的过滤器?您可以使用身份验证中间件和授权属性来重定向登录页面。使用AuthenticationScheme对于您的情况似乎也是合理的。首先使用(我假设你想使用cookie中间件)cookie认证中间件:app.UseCookieAuthentication(newCookieAuthenticationOptions(){AuthenticationScheme="AdminCookieScheme",LoginPath=newPathString("/Admin/Account/Login/"),AccessDeniedPath=newPathString("/Admin/Account/Forbidden/"),AutomaticAuthenticate=true,AutomaticChallenge=true,CookieName="AdminCookies"});然后使用此方案的授权属性:[Authorize(ActiveAuthenticationSchemes="AdminCookieScheme")]另一种选择是使用UseWhen来分离管理员和默认身份验证:app.UseWhen(x=>x.Request.Path.Value.StartsWith("/Admin"),builder=>{builder.UseCookieAuthentication(newCookieAuthenticationOptions(){LoginPath=newPathString("/Admin/Account/Login/"),AccessDeniedPath=newPathString("/Admin/Account/Forbidden/"),AutomaticAuthenticate=true,AutomaticChallenge=true});});然后只需使用授权属性。以上就是《C#学习教程:ASP.NETCore中自定义授权属性》的全部内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
