前面一篇中处理授权类,但是不难发现我们时间上处理业务也是难以扩展,为了做到更好的扩展,我这里需要加入一些参数来做处理,加入什么参数合适呢?
其实在中间件中有 上下文对象 HttpContext,有了这个类我们能做的事情就多了,获取Request 、Response以及RequestServices ,获取DI中注册的服务操作自己的业务做验证
那么怎么来处理这个类呢?
是不是直接把HttpContext直接传过去呢? 其实也是可以的,但是为了安全不暴露一些不必要的操作以及设置对一些属性扩展,我们封装了对一个包装类来重新构造一个密封的中间件上下文对象
internal sealed class AdminChinaDashboardContext : DashboardContext ???{ ???????public AdminChinaDashboardContext(HttpContext httpContext) ??????????: base() ???????{ ???????????if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); ???????????HttpContext = httpContext; ???????????DashboardRequest = new DashboardRequest(httpContext); ???????????DashboardResponse = new DashboardResponse(httpContext); ???????????DashboardRequestServices = httpContext.RequestServices; ???????} ???????public HttpContext HttpContext { get; } ???}
public class DashboardContext ???{ ???????????????public IServiceProvider DashboardRequestServices{ get; protected set; } ???????public DashboardAbstractRequest DashboardRequest { get; set; } ???????public DashboardAbstractResponse DashboardResponse { get; set; } ???}
DashboardRequest、DashboardResponse 对抽象的对于类重写下某些需要的方法即可,比如获取参数之类的(Query & Form) 其他代码略了
这里DashboardContext 作为参数,对外只暴露抽象类提供的一些操作,接下来我们来修改下代码
首先是中间件的地方我们需要把HttpContext传递过去,包装好一个新的DashboardContext中的对象几个运行外部访问的属性
if (_options.Authorization.Any(auth => !auth.IsAuthorize(new AdminChinaDashboardContext(context)))) ???????????????{ ?????????????????????????????????????context.Response.ContentType = "text/html; charset=utf-8"; ???????????????????await context.Response.WriteAsync("这是没有授权的页面"); ???????????????????return; ???????????????}
然后是在实现的授权过滤器里面处理下
public class CustomAuthorizeFilter : IDashboardAuthorizationFilter ???{ ???????public bool IsAuthorize(DashboardContext context) ???????{ ???????????return true; ???????} ???}
我们可以通过上下问对象请求处理,以及获取DI的服务操作
最后我们来继续修改代码,淡然你而已获取DI服务,如下面注释的代码一样,根据你自己的业务处理,这里我写了一个GetQuery方法根据参数测试一下,参数值为admin及可授权
public bool IsAuthorize(DashboardContext context) ???????{ ???????????// XXServices xX= ?context.DashboardRequestServices.GetService(typeof(IXXServices)); ???????????string testval = string.Empty; ???????????try ???????????{ ???????????????testval = context.DashboardRequest.GetQuery("test").Trim(); ???????????} ???????????catch ????????????{ ???????????????return false; ???????????} ??????????????????????if (testval == "admin") ???????????????return true; ???????????else return false; ???????}
访问中间件地址,在不输入以及输入其他参数的情况下都是没有授权的处理
只有当我们的地址输入了admin参数值后,中间件才会有作用
.NetCore 下开发独立的(RPL)含有界面的组件包 (五)授权过滤参数处理
原文地址:https://www.cnblogs.com/liyouming/p/10195697.html