简体   繁体   中英

ASP.Net Core: Where to put app.Use() call to force HTTPS

I've tried a lot of different things and I'm just tired of banging my head on my desk.

I'm creating an ASP.NET Core MVC website. The site works fine until I start trying to test functionality in SSL. I've tried the following links:

The third item kept reappearing on a number of other links, so I attempted multiple ways to get that working. I've moved the code setup into several locations of the Startup class' Configure method. If I place the code segment anywhere before the app.UseMvc() call, I get absolutely nothing: the home page (which isn't under SSL) doesn't come up so I can't follow any links. When I place it after the app.UseMvc() call, any method that uses the [RequireHttps] attribute goes to the "doesn't exist" link. That makes some sense, since I want to use MVC. But how can I test HTTPS?

Where does the code for app.Use(async (context,next)... go?

My current Startup.cs :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
            var sslPort = Configuration.GetValue<int>("iisSetting:iisExpress:sslPort");

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.Use(async (context, next) =>
    {
        if (context.Request.IsHttps)
            await next();
        else
        {
            var sslPortStr = ((sslPort == 0) || (sslPort == 443)) ? string.Empty : ($":{sslPort}");
            var sslUrl = $"https://{context.Request.Host.Host}{sslPort}{context.Request.Path}";
            context.Response.Redirect(sslUrl);
        }
    }); // */
}

UPDATE: (2017/01/26) I've discovered that if I manually enter the SSL port number into the browser URL, the system enters SSL/HTTPS...but then it stays there, even on the pages that don't need security.

What I'm trying to do is have the correct port numbers show up in the URL without manually needing to type them...and only for testing purposes.

you do it in configure services:

services.Configure<MvcOptions>(options =>
{
    options.Filters.Add(new RequireHttpsAttribute());
});

however that will fail (404) if there is no ssl certificate. running directly from kestrel would be different than with IIS Express. With VS 2015 you can check the box in the project properties to use ssl and it will generate a self signed cert for you automatically for IIS Express

You could do what you are doing before app.UseStaticFiles(); . Then any calls for files or MVC routes will be redirected to the secure version.

app.Use(async (context, next) =>
{
    if (context.Request.IsHttps)
        await next();
    else
    {
        var sslPortStr = ((sslPort == 0) || (sslPort == 443)) ? string.Empty : ($":{sslPort}");
        var sslUrl = $"https://{context.Request.Host.Host}{sslPort}{context.Request.Path}";
        context.Response.Redirect(sslUrl);
    }
});
app.UseStaticFiles();

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

I just wrote a small article on this as well: https://joonasw.net/view/enforcing-https-in-aspnet-core .

You can configure it when you add mvc.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.SslPort = 433; // your ssl port no
        options.Filters.Add(new RequireHttpsAttribute());
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM