Benutzer:MovGP0/ASP.NET Core/HTTPS

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      

Enforcing HTTPS

[Bearbeiten | Quelltext bearbeiten]

Custom Middleware

[Bearbeiten | Quelltext bearbeiten]
  • Implement Middleware that redirects to HTTPS when HTTP is used
EnforceHttpsMiddleware.cs
public sealed class EnforceHttpsMiddleware
{
    private RequestDelegate Next { get; }

    public EnforceHttpsMiddleware(RequestDelegate next)
    {
        Next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        HttpRequest request = context.Request;
        if (request.IsHttps) await Next(context);
        var url = ConvertToHttpsUri(request).ToString();
        context.Response.Redirect(url, permanent: true);
    }

    private Uri ConvertToHttpsUri(HttpRequest request)
    {
        // URL has the form
        // scheme://user:password@host:port/path#fragment?querystring
        // user and password are not needed here

        using(var builder = new UriBuilder())
        {
            builder.Scheme = "https";
            builder.Host = request.Host;
            builder.Port = request.Port;
            builder.Path = request.Path;
            builder.Fragment = request.Fragment; 
            builder.Query = request.QueryString;
            return builder.Uri;
        }
    }
}
AppBuilderExtensions.cs
public static class AppBuilderExtensions
{
    public static IApplicationBuilder UseHttpsEnforcement(this IApplicationBuilder app)
    {
        if (app == null) throw new ArgumentNullException(nameof(app));
        return app.UseMiddleware<EnforceHttpsMiddleware>();
    }
}
Startup.Configure
if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseBrowserLink();
}
else
{
    app.UseHttpsEnforcement();
}

Using ASP.NET Core MVC

[Bearbeiten | Quelltext bearbeiten]
using Microsoft.AspNetCore.Mvc;

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute()); // assume every controller has [RequireHttps] attribute
    });
    // ...
}
using Microsoft.AspNetCore.Rewrite;

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var options = new RewriteOptions()
       .AddRedirectToHttps();
    // ...
}

|}