Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
- using Microsoft.EntityFrameworkCore;
- using Swashbuckle.AspNetCore.Swagger;
- using System.Reflection;
- using System.IO;
- using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
- using Newtonsoft.Json.Serialization;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.IdentityModel.Tokens;
- using System.Text;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc.Authorization;
- using Gestcom.Model;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Net.Http.Headers;
- namespace Gestcom
- {
- public class Startup
- {
- public IConfiguration Configuration { get; }
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- // This method gets called by the runtime. Use this method to add services to the container.
- // ConfigureServices define os Serviços usados pelo seu aplicativo (por exemplo, ASP.NET Core MVC, Entity Framework Core, Identity etc.).
- public void ConfigureServices(IServiceCollection services)
- {
- ///////////////////////////////////////////////////////////////
- //// JWT
- ///////////////////////////////////////////////////////////////
- services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(options =>
- {
- options.TokenValidationParameters = new TokenValidationParameters
- {
- ValidateIssuer = false,
- ValidateAudience = false,
- ValidateLifetime = true,
- ValidateIssuerSigningKey = true,
- //ValidIssuer = "https://localhost:5000",
- //ValidAudience = "https://localhost:5000",
- IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
- };
- });
- services.AddAuthorization();
- ///////////////////////////////////////////////////////////////
- //// DATABASE
- ///////////////////////////////////////////////////////////////
- services.AddDbContextPool<GestcomContext>(
- options => options.UseMySql(Configuration.GetConnectionString("gestcom"),
- mySqlOptions =>
- {
- mySqlOptions.ServerVersion(new Version(10, 3, 11), ServerType.MySql);
- }
- ));
- ///////////////////////////////////////////////////////////////
- //// SWAGGER
- ///////////////////////////////////////////////////////////////
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new Info
- {
- Version = "v1",
- Title = "GESTCOM API",
- Description = "Documentação da API",
- TermsOfService = "None",
- Contact = new Contact
- {
- Name = "Gestcom Informática",
- Email = "contato@gestcominformatica.com.br",
- Url = "http://www.sistemagestcom.com.br"
- },
- License = new License
- {
- Name = "Proprietary License - Closed Source",
- Url = "https://en.wikipedia.org/wiki/Software_license"
- }
- });
- /*
- // Permite ao swagger fazer request na api utilizando jwt
- c.AddSecurityDefinition("Bearer", new ApiKeyScheme
- {
- Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
- Name = "Authorization",
- In = "header",
- Type = "apiKey"
- });*/
- c.CustomSchemaIds(x => x.FullName);
- // Set the comments path for the Swagger JSON and UI.
- var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
- var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
- c.IncludeXmlComments(xmlPath);
- });
- ///////////////////////////////////////////////////////////////
- //// COMPRESSION - GZIP
- ///////////////////////////////////////////////////////////////
- services.AddResponseCompression();
- ///////////////////////////////////////////////////////////////
- //// CORS
- ///////////////////////////////////////////////////////////////
- services.AddCors(options =>
- {
- options.AddPolicy("EnableCORS", builder =>
- {
- builder.AllowAnyOrigin()
- .AllowAnyHeader()
- .AllowAnyMethod()
- .AllowCredentials()
- .Build();
- });
- });
- ///////////////////////////////////////////////////////////////
- //// CACHE
- ///////////////////////////////////////////////////////////////
- services.AddResponseCaching();
- ///////////////////////////////////////////////////////////////
- //// MVC
- ///////////////////////////////////////////////////////////////
- services.AddMvc(o =>
- {
- o.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())); // Adiciona o filtro de Authorize por padrão
- })
- .AddXmlSerializerFormatters()
- .AddJsonOptions(options => {
- options.SerializerSettings.ContractResolver = new DefaultContractResolver();
- options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
- })
- .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
- ///////////////////////////////////////////////////////////////
- //// Dependency Injection
- ///////////////////////////////////////////////////////////////
- services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
- services.AddScoped<AuthenticatedUser>();
- services.AddScoped<ParametrizacaoFactory>();
- services.AddScoped<AgendamentoFactory>();
- services.AddScoped<CalculoDV>();
- services.AddScoped<GeraCodigoBarras>();
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- // O método Configure é usado para especificar como o aplicativo responde as solicitações HTTP
- // Configure define o middleware chamado no pipeline de solicitação.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- // Exibe erros em desenvolvimento
- app.UseDeveloperExceptionPage();
- // Exibe diagramas do EF
- //app.AddEfDiagrams<GestcomContext>();
- }
- else
- {
- // Página de erro customizada em produção
- // app.UseExceptionHandler("/error");
- // HTTP Strict Transport Security
- app.UseHsts();
- }
- // JWT
- app.UseAuthentication();
- // Use HTTPS Redirection Middleware to redirect HTTP requests to HTTPS.
- //app.UseHttpsRedirection();
- // GZIP suport
- app.UseResponseCompression();
- // Return static files
- //app.UseStaticFiles();
- //app.UseDirectoryBrowser();
- // Fornece uma página de status code para erros 404, etc
- app.UseStatusCodePages();
- // Enable middleware to serve generated Swagger as a JSON endpoint.
- app.UseSwagger();
- // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
- // specifying the Swagger JSON endpoint.
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "Gestcom");
- c.SupportedSubmitMethods();
- //c.RoutePrefix = string.Empty;
- });
- // Adiciona o header de cors de acordo com a configuração do serviço
- app.UseCors("EnableCORS");
- // Cache
- app.UseResponseCaching();
- app.Use(async (context, next) =>
- {
- context.Response.GetTypedHeaders().CacheControl =
- new CacheControlHeaderValue()
- {
- Public = true,
- MaxAge = TimeSpan.FromSeconds(0),
- NoStore = true,
- NoCache = true,
- MustRevalidate = true,
- };
- context.Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
- await next();
- });
- // Add MVC to the request pipeline.
- app.UseMvc();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement