You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
235 lines
8.2 KiB
235 lines
8.2 KiB
using DealerSelection.Common.Helpers;
|
|
using DealerSelection.Common.Middleware;
|
|
using Lamar;
|
|
using Lamar.Microsoft.DependencyInjection;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Http.Json;
|
|
using Microsoft.AspNetCore.HttpOverrides;
|
|
using Microsoft.AspNetCore.Mvc.Formatters;
|
|
using Microsoft.AspNetCore.ResponseCompression;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Logging.ApplicationInsights;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using Microsoft.OpenApi.Models;
|
|
using System.IO.Compression;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace DealerSelection.Common.CommonBaseClass;
|
|
|
|
public abstract class StartupBase
|
|
{
|
|
public WebApplication CreateHostBuilder(string[] args)
|
|
{
|
|
try
|
|
{
|
|
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
|
|
|
|
builder.Host.UseLamar((context, registry) =>
|
|
{
|
|
registry.IncludeRegistry(CreateDIRegistry());
|
|
registry.AddControllers();
|
|
});
|
|
|
|
SetupService(builder.Services);
|
|
SetupSwaggerOptions(builder);
|
|
|
|
#region AzureLogging
|
|
|
|
AzureLogging(builder);
|
|
|
|
#endregion
|
|
|
|
#region JWT Authentication
|
|
JWTAuthentication(builder);
|
|
#endregion
|
|
|
|
WebApplication app = builder.Build();
|
|
app.UseResponseCompression();
|
|
|
|
app.UseRouting();
|
|
|
|
if (Configuration.ConfigurationHelper.GetSetting<string>("BrowseSwagger", true) == "True")
|
|
SetupSwagger(app);
|
|
|
|
app.UseCors(x => x
|
|
//.WithOrigins("https://www.ktmindia.com", "https://www.triumphmotorcyclesindia.com") //Used for PROD
|
|
.AllowAnyOrigin() //Only used for Development
|
|
.AllowAnyMethod()
|
|
.AllowAnyHeader());
|
|
|
|
//app.UseMiddleware<UserAgentBlackListMiddleware>();
|
|
app.UseMiddleware<SwaggerRootRoutingMiddleware>();
|
|
//app.UseMiddleware<AuthenticationMiddleware>();
|
|
// app.UseMiddleware<LoggingMiddleware>();
|
|
|
|
app.UseForwardedHeaders(new ForwardedHeadersOptions
|
|
{
|
|
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
|
|
});
|
|
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
app.UseStaticFiles();
|
|
// app.MapControllers();
|
|
|
|
app.UseEndpoints(endpoints =>
|
|
{
|
|
endpoints.MapControllers();
|
|
endpoints.MapHealthChecks("/health");
|
|
});
|
|
return app;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine(ex);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private void SetupService(IServiceCollection services)
|
|
{
|
|
//Caching
|
|
services.AddMemoryCache();
|
|
|
|
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
|
services.AddMvc(options => options.Filters.Add(new ExceptionFilterBase()));
|
|
services.AddMvc(options => options.OutputFormatters.Add(new XmlSerializerOutputFormatter()));
|
|
|
|
services.AddResponseCompression(options =>
|
|
{
|
|
options.Providers.Add<BrotliCompressionProvider>();
|
|
options.EnableForHttps = true;
|
|
});
|
|
|
|
services.Configure<GzipCompressionProviderOptions>(options =>
|
|
{
|
|
options.Level = CompressionLevel.Optimal;
|
|
});
|
|
|
|
services.AddResponseCompression(options =>
|
|
{
|
|
options.Providers.Add<GzipCompressionProvider>();
|
|
options.EnableForHttps = true;
|
|
});
|
|
|
|
services.AddEndpointsApiExplorer();
|
|
services.AddControllers().AddXmlDataContractSerializerFormatters();
|
|
services.AddHealthChecks();
|
|
services.Configure<JsonOptions>(options =>
|
|
{
|
|
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
|
|
});
|
|
services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
|
|
{
|
|
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
|
|
});
|
|
}
|
|
|
|
private void AzureLogging(WebApplicationBuilder builder)
|
|
{
|
|
builder.Logging.AddApplicationInsights(
|
|
configureTelemetryConfiguration: (config) => config.ConnectionString =
|
|
builder.Configuration.GetConnectionString("AZURE_LOGGING"),
|
|
configureApplicationInsightsLoggerOptions: (options) => { }
|
|
);
|
|
builder.Logging.AddFilter<ApplicationInsightsLoggerProvider>("traces", LogLevel.Trace);
|
|
}
|
|
|
|
|
|
private void JWTAuthentication(WebApplicationBuilder builder)
|
|
{
|
|
List<string> audiences = new List<string>();
|
|
string[] getAudiences = builder.Configuration["Jwt:Audience"].Split(',');
|
|
foreach (var audience in getAudiences)
|
|
{
|
|
audiences.Add(audience);
|
|
}
|
|
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
|
|
{
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = true,
|
|
ValidateAudience = true,
|
|
ValidateLifetime = true,
|
|
ValidateIssuerSigningKey = true,
|
|
ValidIssuer = builder.Configuration["Jwt:Issuer"],
|
|
ValidAudiences = new List<string>(audiences),
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
|
|
};
|
|
});
|
|
}
|
|
|
|
private void SetupSwaggerOptions(WebApplicationBuilder builder)
|
|
{
|
|
builder.Services.AddSwaggerGen(options =>
|
|
{
|
|
|
|
SwashbuckleSchemaHelper schemaHelper = new SwashbuckleSchemaHelper();
|
|
//handle checking for duplicate return types and makes the name unique
|
|
options.CustomSchemaIds(type => schemaHelper.GetSchemaId(type));
|
|
// options.DocumentFilter<HideMethodsExternallyFilter>();
|
|
// options.OperationFilter<SecurityRequirementsOperationFilter>();
|
|
|
|
#region Swagger Customization For Authentication
|
|
|
|
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
|
{
|
|
Name = "Authorization",
|
|
Type = SecuritySchemeType.Http,
|
|
Scheme = "Bearer",
|
|
//Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme },
|
|
BearerFormat = "JWT",
|
|
In = ParameterLocation.Header,
|
|
Description = "Please Enter a Valid JWT Token",
|
|
});
|
|
options.AddSecurityRequirement(new OpenApiSecurityRequirement
|
|
{
|
|
{
|
|
new OpenApiSecurityScheme
|
|
{
|
|
Reference = new OpenApiReference
|
|
{
|
|
Type=ReferenceType.SecurityScheme,
|
|
Id="Bearer"
|
|
}
|
|
},
|
|
new string[]{}
|
|
}
|
|
});
|
|
#endregion
|
|
|
|
options.SwaggerDoc("v1", new OpenApiInfo
|
|
{
|
|
Version = "v1",
|
|
Title = "Dealer Selection API",
|
|
Description = "Web API for Dealer Selection Management"
|
|
});
|
|
options.EnableAnnotations();
|
|
|
|
string xmlFileName = $"{Assembly.GetEntryAssembly()!.GetName().Name}.xml";
|
|
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFileName));
|
|
|
|
});
|
|
}
|
|
|
|
private static void SetupSwagger(WebApplication app)
|
|
{
|
|
app.UseSwagger(c =>
|
|
{
|
|
c.RouteTemplate = "help/ui/{documentName}/swagger.json";
|
|
});
|
|
app.UseSwaggerUI(c =>
|
|
{
|
|
c.SwaggerEndpoint("/help/ui/v1/swagger.json", "Sample API");
|
|
c.RoutePrefix = "help/ui";
|
|
c.InjectStylesheet("/CustomContent/SwaggerHeader.css");
|
|
});
|
|
}
|
|
protected abstract ServiceRegistry CreateDIRegistry();
|
|
}
|