/// <summary> /// 处理请求 /// 接受请求,映射到对应的Service /// <param name="context"></param> /// <returns></returns> public async Task Invoke(HttpContext context) { using (logger.BeginScope(new KeyValuePair <string, string>("middleware", "xframework.servicehandler"))) { var router = GetBaseRouter(context.Request.Path); logger.Info("Request path : {0}, router : {1}", context.Request.Path, router); var service = ServiceHandlerProvider.GetInstance().GetService(router, context.RequestServices); if (service == null) { // 自身无法处理的话交给下一个中间件处理, 完成后退出 await next(context); return; } using (logger.BeginScope(new KeyValuePair <string, string>("servicehandler", service.Name))) { // 强制使用UTF8作为返回的Encoding context.Response.ContentType = "application/json; charset=UTF-8"; // 这里要注意是,如果能被这个Middleware处理,它则是最后一个中间件,如果不能被它处理,则放过,让404中间件进行处理 var response = await service.Process(context); await context.Response.WriteAsync(response); } } }
/// <summary> /// 将XFramework架构添加到服务中,便于引入Ioc /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddXServiceHandler (this IServiceCollection services, IConfiguration configuration, IHostingEnvironment environment) { var setting = AppSetting.GetInstance(); // 初始化配置文件 configuration.Bind(setting); setting.Enviroment = environment; try { // 初始化 ServiceHandlerProvider.GetInstance().ConfigService(services); } catch (Exception e) { logger.Error(e, "Service handler start up failure"); // 销毁LogProvider,确保日志记录完整 LogProvider.GetInstance().Dispose(); throw e; } return(services); }