Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable / Disable SSL on ASP.NET Core projects in Development

Tags:

asp.net-core

On an ASP.NET Core project, I am using SSL in Production so I have in Startup:

public void ConfigureServices(IServiceCollection services) {
  services.AddMvc(x => {
    x.Filters.Add(new RequireHttpsAttribute());
  });  
  // Remaining code ...
}

public void Configure(IApplicationBuilder builder, IHostingEnvironment environment, ILoggerFactory logger, IApplicationLifetime lifetime) {
  RewriteOptions rewriteOptions = new RewriteOptions();
  rewriteOptions.AddRedirectToHttps();
  builder.UseRewriter(rewriteOptions);
  // Remaining code ...
}

It works fine in Production but not in Development. I would like to either:

  1. Disable SSL in Development;
  2. Make SSL work in Development because with current configuration it is not. Do I need to set any PFX files on my local machine?
    I am working on multiple projects so that might create problems?
like image 755
Miguel Moura Avatar asked May 05 '17 16:05

Miguel Moura


People also ask

How do I enable SSL for a .NET project in Visual Studio?

For local testing, you can enable SSL in IIS Express from Visual Studio. In the Properties window, set SSL Enabled to True. Note the value of SSL URL; use this URL for testing HTTPS connections.

How do I disable HTTPS in .NET core API?

If we want to disable HTTP for the asp.net code, we just need to remove lines 11 to 13 and the same for HTTPS, if we want to disable HTTPS, just remove lines 14 to 16 and comment out app. UseHttpsRedirection(); in Program.


2 Answers

You can configure a service using the IConfigureOptions<T> interface.

internal class ConfigureMvcOptions : IConfigureOptions<MvcOptions>
{
    private readonly IHostingEnvironment _env;
    public ConfigureMvcOptions(IHostingEnvironment env)
    {
        _env = env;
    }

    public void Configure(MvcOptions options)
    {
        if (_env.IsDevelopment())
        {
            options.SslPort = 44523;
        }
        else
        {
            options.Filters.Add(new RequireHttpsAttribute());
        }
    }
}

Then, add this class as a singleton:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    var builder = services.AddMvc();
    services.AddSingleton<IConfigureOptions<MvcOptions>, ConfigureMvcOptions>();
}

Concerning the SSL point, you can easily use SSL using IIS Express (source)

Configure SSL in SSL

like image 50
meziantou Avatar answered Oct 11 '22 03:10

meziantou


If you don't want to use IIS Express then delete the https-address in Project Properties -> Debug section -> Under "Web Server Settings" -> Uncheck "Enable SSL".

ProjectProperties

like image 38
albin Avatar answered Oct 11 '22 03:10

albin