Esempio n. 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        /// <summary>
        /// 服务容器注入方法
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(logging => logging.AddFileLogger().AddCloudLogger().AddDBLogger(ExceptionsHelper.Log));
            services.AddCors();
            services.AddResponseCompression();

            services.AddCodePageProvider();
            services.AddCacheManager();
            services.AddDbAdapter();
            services.AddIPLocator(DictHelper.ConfigIPLocator);
            services.AddOnlineUsers();
            services.AddSignalR().AddJsonProtocol(op => op.PayloadSerializerOptions.AddDefaultConverters());
            services.AddSignalRExceptionFilterHandler <SignalRHub>(async(client, ex) => await client.SendMessageBody(ex).ConfigureAwait(false));
            services.AddBootstrapAdminAuthentication(Configuration)
            .AddGitee(OAuthHelper.Configure)
            .AddGitHub(OAuthHelper.Configure)
            .AddTencent(OAuthHelper.Configure)
            .AddAlipay(OAuthHelper.Configure);
            services.AddAuthorization(options => options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireBootstrapAdminAuthorizate().Build());
            services.AddButtonAuthorization(MenuHelper.AuthorizateButtons);
            services.AddBootstrapAdminBackgroundTask();
            services.AddHttpClient <GiteeHttpClient>();
            services.AddAdminHealthChecks();
            services.AddSMSProvider();

            services.AddSwagger();
            services.AddApiVersioning(option =>
            {
                option.DefaultApiVersion = new ApiVersion(1, 0);
                option.ReportApiVersions = true;
                option.AssumeDefaultVersionWhenUnspecified = true;
                option.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("api-version"), new QueryStringApiVersionReader("api-version"));
            });
            services.AddControllersWithViews(options =>
            {
                options.Filters.Add <BootstrapAdminAuthorizeFilter>();
                options.Filters.Add <ExceptionFilter>();
                options.Filters.Add <SignalRExceptionFilter <SignalRHub> >();
            }).AddJsonOptions(op => op.JsonSerializerOptions.AddDefaultConverters());
            services.AddRazorPages();
            services.AddServerSideBlazor().AddCircuitOptions(options =>
            {
                if (Enviroment.IsDevelopment())
                {
                    options.DetailedErrors = true;
                }
            });
            services.AddDisplayNames();
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Autenticação
            var tokenConfigurations = new TokenConfiguration();

            new ConfigureFromConfigurationOptions <TokenConfiguration>(
                Configuration.GetSection("TokenConfigurations")
                ).Configure(tokenConfigurations);

            services.AddSingleton(tokenConfigurations);
            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = tokenConfigurations.Issuer,
                    ValidAudience    = tokenConfigurations.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenConfigurations.Secret))
                };
            });

            services.AddAuthorization(auth => {
                auth.AddPolicy(
                    "Bearer",
                    new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build()
                    );
            });
            //=-=-=-=-==-=-=-=-==-=-=-=-==-=-=-=-==-=-=-=-=

            services.AddCors(options => options.AddDefaultPolicy(builder => {
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            }));

            services.AddControllers();

            var connection = Configuration["MySQLConnection:MySQLConnectionString"];

            services.AddDbContext <MySQLContext>(options => options.UseMySql(connection, ServerVersion.AutoDetect(connection)));

            if (Enviroment.IsDevelopment())
            {
                MigrateDataBase(connection);
            }

            //Passa a receber e enviar json ou xml, de acordo com a propriedade accept no header da requisição
            services.AddMvc(options => {
                options.RespectBrowserAcceptHeader = true;
                options.FormatterMappings.SetMediaTypeMappingForFormat("xml", MediaTypeHeaderValue.Parse("application/xml"));
                options.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValue.Parse("application/json"));
            }).AddXmlSerializerFormatters();

            var filterOptions = new HyperMediaFilterOptions();

            filterOptions.ContentResponseEnricherList.Add(new PersonEnricher());
            filterOptions.ContentResponseEnricherList.Add(new BookEnricher());
            services.AddSingleton(filterOptions);

            //Versionamento das APIs
            services.AddApiVersioning();

            //Suporte ao Swagger
            services.AddSwaggerGen(c => {
                c.SwaggerDoc(
                    "v1",
                    new OpenApiInfo {
                    Title       = "REST API's from 0 to Azure with ASP.NET Core 5 and Docker",
                    Version     = "v1",
                    Description = "API RESTful developed in course 'REST API's from 0 to Azure with ASP.NET Core 5 and Docker'",
                    Contact     = new OpenApiContact {
                        Name = "Wesley Silva",
                        Url  = new Uri("https://github.com/wesleysiilva")
                    }
                });
            });

            //Injeção de dependencia, referencia a interface e a implementação da API.
            //=======================================================================

            //Upload/Download files
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <IFileBusiness, FileBusinessImplementation>();

            //Person
            services.AddScoped <IPersonBusiness, PersonBusinessImplementation>();

            //Books
            services.AddScoped <IBookBusiness, BookBusinessImplementation>();

            //Token
            services.AddScoped <ILoginBusiness, LoginBusinessImplementation>();
            services.AddTransient <ITokenService, TokenService>();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IPersonRepository, PersonRepository>();

            //Generic
            services.AddScoped(typeof(IRepository <>), typeof(GenericRepository <>));

            //=======================================================================
        }