TLS middleware in ASP.NET Core

Within your ASP.NET Core API, you may wish to restrict access to only those requests made over TLS.

You can achieve this by for all requests by developing a custom piece of middleware:

app.Use(async (context, next) =>
{
  if (context.Request.IsHttps)
  {
    await next();
    return;
  }

  context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
  context.Response.ContentType = "text/plain";
  await context.Response.WriteAsync(
    "Access denied. Use TLS for API access.");
});

You can improve this through wrapping the handler in a custom extension method:

public static class ApplicationBuilderExtensions
{
  public static IApplicationBuilder UseRequireTls(
    this IApplicationBuilder builder)
  {
    if (builder == null)
    {
      throw new ArgumentNullException(nameof(builder));
    }

    return builder.Use(
      async (context, next) =>
          {
              if (context.Request.IsHttps)
              {
                  await next();
                  return;
              }

              context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
              context.Response.ContentType = "text/plain";
              await context.Response.WriteAsync(
                "Access denied. Use TLS for API access.");
          });            
  }
}

Usage:

  app.UseRequireTls();