Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.82 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.AspNetCore.HttpsPolicy;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.Extensions.Configuration;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using Microsoft.Extensions.Logging;
  12. using Microsoft.Extensions.Options;
  13. using Microsoft.EntityFrameworkCore;
  14. using Swashbuckle.AspNetCore.Swagger;
  15. using System.Reflection;
  16. using System.IO;
  17. using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
  18. using Newtonsoft.Json.Serialization;
  19. using Microsoft.AspNetCore.Authentication.JwtBearer;
  20. using Microsoft.IdentityModel.Tokens;
  21. using System.Text;
  22. using Microsoft.AspNetCore.Authorization;
  23. using Microsoft.AspNetCore.Mvc.Authorization;
  24. using Gestcom.Model;
  25. using Microsoft.AspNetCore.Http;
  26. using Microsoft.Net.Http.Headers;
  27.  
  28. namespace Gestcom
  29. {
  30.     public class Startup
  31.     {
  32.         public IConfiguration Configuration { get; }
  33.  
  34.         public Startup(IConfiguration configuration)
  35.         {
  36.             Configuration = configuration;
  37.         }
  38.  
  39.         // This method gets called by the runtime. Use this method to add services to the container.
  40.         // ConfigureServices define os Serviços usados pelo seu aplicativo (por exemplo, ASP.NET Core MVC, Entity Framework Core, Identity etc.).
  41.         public void ConfigureServices(IServiceCollection services)
  42.         {
  43.             ///////////////////////////////////////////////////////////////
  44.             //// JWT
  45.             ///////////////////////////////////////////////////////////////
  46.             services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  47.                     .AddJwtBearer(options =>
  48.                     {
  49.                         options.TokenValidationParameters = new TokenValidationParameters
  50.                         {
  51.                             ValidateIssuer = false,
  52.                             ValidateAudience = false,
  53.                             ValidateLifetime = true,
  54.                             ValidateIssuerSigningKey = true,
  55.  
  56.                             //ValidIssuer = "https://localhost:5000",
  57.                             //ValidAudience = "https://localhost:5000",
  58.                             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
  59.                         };
  60.                     });
  61.  
  62.             services.AddAuthorization();
  63.  
  64.             ///////////////////////////////////////////////////////////////
  65.             //// DATABASE
  66.             ///////////////////////////////////////////////////////////////
  67.             services.AddDbContextPool<GestcomContext>(
  68.                 options => options.UseMySql(Configuration.GetConnectionString("gestcom"),
  69.                     mySqlOptions =>
  70.                     {
  71.                         mySqlOptions.ServerVersion(new Version(10, 3, 11), ServerType.MySql);
  72.                     }
  73.             ));
  74.  
  75.             ///////////////////////////////////////////////////////////////
  76.             //// SWAGGER
  77.             ///////////////////////////////////////////////////////////////
  78.             services.AddSwaggerGen(c =>
  79.             {
  80.                 c.SwaggerDoc("v1", new Info
  81.                 {
  82.                     Version = "v1",
  83.                     Title = "GESTCOM API",
  84.                     Description = "Documentação da API",
  85.                     TermsOfService = "None",
  86.                     Contact = new Contact
  87.                     {
  88.                         Name = "Gestcom Informática",
  89.                         Email = "contato@gestcominformatica.com.br",
  90.                         Url = "http://www.sistemagestcom.com.br"
  91.                     },
  92.                     License = new License
  93.                     {
  94.                         Name = "Proprietary License - Closed Source",
  95.                         Url = "https://en.wikipedia.org/wiki/Software_license"
  96.                     }
  97.                 });
  98.  
  99.                 /*
  100.                 // Permite ao swagger fazer request na api utilizando jwt
  101.                 c.AddSecurityDefinition("Bearer", new ApiKeyScheme
  102.                 {
  103.                     Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
  104.                     Name = "Authorization",
  105.                     In = "header",
  106.                     Type = "apiKey"
  107.                 });*/
  108.  
  109.                 c.CustomSchemaIds(x => x.FullName);
  110.  
  111.                 // Set the comments path for the Swagger JSON and UI.
  112.                 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
  113.                 var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
  114.                 c.IncludeXmlComments(xmlPath);
  115.             });
  116.  
  117.             ///////////////////////////////////////////////////////////////
  118.             //// COMPRESSION - GZIP
  119.             ///////////////////////////////////////////////////////////////
  120.             services.AddResponseCompression();
  121.  
  122.             ///////////////////////////////////////////////////////////////
  123.             //// CORS
  124.             ///////////////////////////////////////////////////////////////
  125.             services.AddCors(options =>
  126.             {
  127.                 options.AddPolicy("EnableCORS", builder =>
  128.                 {
  129.                     builder.AllowAnyOrigin()
  130.                            .AllowAnyHeader()
  131.                            .AllowAnyMethod()
  132.                            .AllowCredentials()
  133.                            .Build();
  134.                 });
  135.             });
  136.  
  137.             ///////////////////////////////////////////////////////////////
  138.             //// CACHE
  139.             ///////////////////////////////////////////////////////////////
  140.             services.AddResponseCaching();
  141.  
  142.             ///////////////////////////////////////////////////////////////
  143.             //// MVC
  144.             ///////////////////////////////////////////////////////////////
  145.             services.AddMvc(o =>
  146.             {
  147.                 o.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())); // Adiciona o filtro de Authorize por padrão
  148.             })
  149.             .AddXmlSerializerFormatters()
  150.             .AddJsonOptions(options => {
  151.               options.SerializerSettings.ContractResolver = new DefaultContractResolver();
  152.               options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
  153.             })
  154.             .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  155.  
  156.             ///////////////////////////////////////////////////////////////
  157.             //// Dependency Injection
  158.             ///////////////////////////////////////////////////////////////
  159.             services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  160.               services.AddScoped<AuthenticatedUser>();
  161.             services.AddScoped<ParametrizacaoFactory>();
  162.             services.AddScoped<AgendamentoFactory>();
  163.             services.AddScoped<CalculoDV>();
  164.             services.AddScoped<GeraCodigoBarras>();
  165.  
  166.         }
  167.  
  168.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  169.         // O método Configure é usado para especificar como o aplicativo responde as solicitações HTTP
  170.         // Configure define o middleware chamado no pipeline de solicitação.
  171.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  172.         {
  173.             if (env.IsDevelopment())
  174.             {
  175.                 // Exibe erros em desenvolvimento
  176.                 app.UseDeveloperExceptionPage();
  177.  
  178.                 // Exibe diagramas do EF
  179.                 //app.AddEfDiagrams<GestcomContext>();
  180.             }
  181.             else
  182.             {
  183.                 // Página de erro customizada em produção
  184.                 // app.UseExceptionHandler("/error");
  185.  
  186.                 // HTTP Strict Transport Security
  187.                 app.UseHsts();
  188.             }
  189.  
  190.             // JWT
  191.             app.UseAuthentication();
  192.  
  193.             // Use HTTPS Redirection Middleware to redirect HTTP requests to HTTPS.
  194.             //app.UseHttpsRedirection();
  195.  
  196.             // GZIP suport
  197.             app.UseResponseCompression();
  198.  
  199.             // Return static files
  200.             //app.UseStaticFiles();
  201.             //app.UseDirectoryBrowser();
  202.  
  203.             // Fornece uma página de status code para erros 404, etc
  204.             app.UseStatusCodePages();
  205.  
  206.             // Enable middleware to serve generated Swagger as a JSON endpoint.
  207.             app.UseSwagger();
  208.  
  209.             // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
  210.             // specifying the Swagger JSON endpoint.
  211.             app.UseSwaggerUI(c =>
  212.             {
  213.                 c.SwaggerEndpoint("/swagger/v1/swagger.json", "Gestcom");
  214.                 c.SupportedSubmitMethods();
  215.                 //c.RoutePrefix = string.Empty;
  216.             });
  217.  
  218.             // Adiciona o header de cors de acordo com a configuração do serviço
  219.             app.UseCors("EnableCORS");
  220.  
  221.             // Cache
  222.             app.UseResponseCaching();
  223.  
  224.             app.Use(async (context, next) =>
  225.             {
  226.                 context.Response.GetTypedHeaders().CacheControl =
  227.                     new CacheControlHeaderValue()
  228.                     {
  229.                         Public = true,
  230.                         MaxAge = TimeSpan.FromSeconds(0),
  231.                         NoStore = true,
  232.                         NoCache = true,
  233.                         MustRevalidate = true,
  234.                     };
  235.                 context.Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
  236.  
  237.                 await next();
  238.             });
  239.  
  240.             // Add MVC to the request pipeline.
  241.             app.UseMvc();
  242.         }
  243.     }
  244. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement