public async Task Consume(ConsumeContext <Microservices.Common.Messages.GlobalExceptionMessage> context)
        {
            var message = new GlobalExceptionMessage
            {
                ApplicationName       = context.Message.ApplicationName,
                ExceptionMessage      = context.Message.ExceptionMessage,
                FunctionName          = context.Message.FunctionName,
                InnerExceptionMessage = context.Message.InnerExceptionMessage,
                OccurredAt            = context.Message.OccurredAt,
                StackTrace            = context.Message.StackTrace,
                UserName = context.Message.UserName
            };
            await _dbContext.GlobalExceptionMessages.AddAsync(message);

            await _dbContext.SaveChangesAsync();

            _logger.LogError(context.Message.ExceptionMessage);
        }
Beispiel #2
0
        /// <summary>
        /// ConfigureServices
        /// </summary>
        /// <param name="services">services</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            //注入全局异常配置项
            GlobalExceptionMessage globalOptions = new GlobalExceptionMessage();

            Configuration.GetSection(nameof(GlobalExceptionMessage)).Bind(globalOptions);

            #region 数据库配置

            var connection = Configuration.GetConnectionString("DefaultConnection");
            //工作单元注入,每次请求创建一个实例,避免多个请求争抢同一context
            services.AddScoped <IUnitOfWork>(d => new UnitOfWork(connection));


            #endregion



            #region 权限相关

            //jwt
            var jwtOptions = new JwtOptions();
            Configuration.GetSection(nameof(JwtOptions)).Bind(jwtOptions);
            //注入JWT授权配置项
            services.Configure <JwtOptions>(Configuration.GetSection(nameof(JwtOptions)));
            var keyByteArray = Encoding.ASCII.GetBytes(jwtOptions.SymmetricKeyAsBase64);
            var signingKey   = new SymmetricSecurityKey(keyByteArray);
            //增加授权
            services.AddAuthorization(auth =>
            {
                //配置授权方式
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser()
                               .Build());
            });
            //授权参数
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer      = jwtOptions.Issuer,
                ValidateAudience = true,
                ValidAudience    = jwtOptions.Audience,
                ValidateLifetime = true,
                ClockSkew        = TimeSpan.Zero
            };
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                //使用https
                //o.RequireHttpsMetadata = true;
                o.TokenValidationParameters = tokenValidationParameters;
            });
            services.AddScoped <AuthFactory>();

            #endregion

            #region 注入http请求

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IPrincipal>(
                p => p.GetService <IHttpContextAccessor>().HttpContext.User
                );
            services.AddScoped <IUserContext, UserContext>();

            #endregion

            //跨域配置,项目部署时若以虚拟目录方式创建站点,删除该配置
            services.AddCors(options =>
                             options.AddPolicy(
                                 "AllowAllMethods",
                                 builder => builder.AllowAnyOrigin() /*.WithOrigins(urls)*/
                                 .AllowAnyMethod()
                                 .AllowAnyHeader()
                                 .AllowCredentials()
                                 .WithExposedHeaders("Content-Disposition")
                                 ));
            //全局过滤器
            services.AddMvc(options =>
            {
                //全局异常捕获
                options.Filters.Add(new HttpGlobalExceptionFilter(_env, globalOptions, new ExceptionProcess()));
                //请求返回结果捕获
                options.Filters.Add <HttpResultFilter>();
            });

            #region AutoMapper
            //automapper注册映射配置
            var mappConfiger = AutoMapperConfig.RegisterMappings();
            services.AddAutoMapper(cfg => mappConfiger.CreateMapper());
            services.AddSingleton <IMapper, Mapper>();

            #endregion

            #region swagger
            //swagger生成调试
            if (Convert.ToBoolean(AppSettings["SwaggerEnable"]))
            {
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("BaseAPI", new Info {
                        Title = "BaseAPI"
                    });
                    c.OrderActionsBy((apiDesc) => $"{apiDesc.HttpMethod}");
                    c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                    {
                        Description =
                            "JWT 授权设置: \"Authorization: Bearer {token}\"",
                        Name = "Authorization",
                        In   = "header",
                        Type = "apiKey"
                    });
                    c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                        { "Bearer", Enumerable.Empty <string>() }
                    });
                    var app = PlatformServices.Default.Application;
                    var xml = Path.Combine(app.ApplicationBasePath, "NetCoreFrame.WebApi.xml");
                    c.IncludeXmlComments(xml);
                });
            }
            #endregion
        }