Skip to content

Host template guidance

Thang Chung edited this page Dec 28, 2018 · 3 revisions

Templates

  • Rest Template
    • Standard Template
    • EfCore Template
    • MongoDb Template
  • gRPC template
    • Standard gRPC Template
    • EfCore gRPC Template
    • MongoDb gPRC Template

List of features in the templates

No. Feature Type of feature Description Guidance
1. EfCore or MongoDb Opt-in Database Providers: Entity Framework(SQL Server, MySQL, and SQLite) and MongoDb link
2. RestClient Out of the box The Rest client along with failure resilient mechanism which uses to call to another endpoints link
3. DomainEventBus Out of the box In-memory domain event bus which allows another subscribers to subscribe and publish other events to distributed bus. link
4. CleanArch Opt-in Build-in with simplify Clean Architecture elements which help developers easy to organize the code with clean style link
5. Cache Out of the box Output cache for WebAPI link
6. ApiVersion Opt-in Help to organize the API along with versioning its link
7. Mvc Out of the box Add Mvc code style for WebAPI link
8. DetailException Out of the box Exception handling with details of stack trace in clean structure which helps a lot in debug and error trace link
9. AuthN Opt-in Enabled ability which helps to do authentication on the API with the effortless works link
10. OpenApi Opt-in Support the OpenApi standard with the Swagger file generated out of the box. link
11. Cors Out of the box Support CORS mechanism then we can configure the white list of accessing sites. link
12. HeaderForward Out of the box Help to forward x-forward-for and x-forward-proto headers in case we host behind of the reverse proxy or load balancer link
13. OpenApi-Profiler Opt-in Enable the profiler for WebAPI which is we can see how many seconds does it take to do the request to the WebAPI link
14. Health Out of the box Expose /healthz endpoint so that the orchestrator like Docker Swarm or Kubernetes can check that to make sure the readiness of the application link

Additional features

No. Feature Type of feature Description Guidance
1. In-Process Bus Opt-in Help to publish and subscribe the domain events in simplify cases link
2. Redis Bus Opt-in Help to publish and subscribe the domain events in high scalability style using Redis Broker link
3. Kafka Bus Opt-in Help to publish and subscribe the domain events in high scalability style using Kafka Broker link
4. MessagePack Opt-in Support MessagePack for WebAPI link
5. ResponseCompression Opt-in Support brotli compression standard link

Order middlewares in AppBuilder

  1. Log exception handler
app.UseMiddleware<LogHandlerMiddleware>();
  1. Response cache
app.UseResponseCaching();
  1. Configure Exception handling
if (env.IsDevelopment())
{
  app.UseDeveloperExceptionPage();
  app.UseDatabaseErrorPage();

  if (feature.IsEnabled("OpenApi:Profiler"))
    app.UseMiniProfiler();
}
else
{
  app.UseExceptionHandler("/error");
}
app.UseExceptionHandlerCore();
app.UseMiddleware<ErrorHandlerMiddleware>();
  1. BeatPulse healthcheck
app
  .UseBeatPulse(options =>
  {
    options.ConfigurePath("healthz") //default hc
      .ConfigureTimeout(1500) // default -1 infinitely
      .ConfigureDetailedOutput(true, true); //default (true,false)
  });
  1. Miniprofiler on API
if (feature.IsEnabled("OpenApi:Profiler"))
  app.UseMiddleware<MiniProfilerMiddleware>();
  1. liveness endpoint
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  app.Map("/liveness", lapp => lapp.Run(async ctx => ctx.Response.StatusCode = 200));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  1. Re-configure the base path (need for hosting in sub-directory on Kubernetes)
var basePath = config.GetBasePath();
if (!string.IsNullOrEmpty(basePath))
{
  var logger = loggerFactory.CreateLogger("init");
  logger.LogInformation($"Using PATH BASE '{basePath}'");
  app.UsePathBase(basePath);
}
  1. ForwardHeaders
if (!env.IsDevelopment())
  app.UseForwardedHeaders();
  1. Cors
app.UseCors("CorsPolicy");
  1. AuthN
if (feature.IsEnabled("AuthN"))
  app.UseAuthentication();
  1. Mvc
app.UseMvc();
  1. Open API
if (feature.IsEnabled("OpenApi"))
  app.UseSwagger();

if (feature.IsEnabled("OpenApi:OpenApiUI"))
{
  // to make it work, we need to create an application with swagger_app name
  app.UseSwaggerUI(
    c =>
    {
      var provider = app.ApplicationServices.GetRequiredService<IApiVersionDescriptionProvider>();
      foreach (var description in provider.ApiVersionDescriptions)
        c.SwaggerEndpoint(
          $"{basePath}swagger/{description.GroupName}/swagger.json",
          description.GroupName.ToUpperInvariant());

      if (feature.IsEnabled("AuthN"))
      {
        c.OAuthClientId("swagger_id");
        c.OAuthClientSecret("secret".Sha256());
        c.OAuthAppName("swagger_app");
        c.OAuth2RedirectUrl($"{config.GetExternalCurrentHostUri()}/swagger/oauth2-redirect.html");
      }

      if (feature.IsEnabled("OpenApi:Profiler"))
        c.IndexStream = () =>
          typeof(Infrastructure.AspNetCore.All.ServiceCollectionExtensions)
            .GetTypeInfo()
            .Assembly
            .GetManifestResourceStream("NetCoreKit.Infrastructure.AspNetCore.All.Swagger.index.html");
    });
}
Clone this wiki locally