Enabling SSL in an ASP.NET Core application

To enable SSL in our ASP.NET Core project, we can add filters in the AddMvc method defined in the ConfigureServices method of our Startup class. Filters are used to filter the HTTP calls and take certain actions:

services.AddMvc(options => 
{ 
  options.Filters.Add(new RequireHttpsAttribute()) 
}); 

Filters added in the AddMvc method are global filters and interrupt all HTTP requests, irrespective of a specific controller or action. We added the RequireHttpsAttribute filter, which validates the incoming request and checks whether the request is on HTTP or HTTPS. If the request is on HTTP, it will auto redirect the request to HTTPS and use the default port, which is 443 in the case of HTTPS. Adding the preceding code snippet is not enough to run our application on SSL. We also need to tell the launchSettings.json file to use the HTTPS port and enable SSL for our project. One way to do this is to enable SSL from the Debug tab in the Visual Studio project properties window, which is shown as follows:

This also modifies the launchSettings.json file and adds the SSL. Another way is to directly modify the port number from the launchSetttings.json file itself. Here is the launchsettings.json file that uses port 44326 for SSL, which has been added under iisSettings:

{ 
  "iisSettings": { 
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": { 
      "applicationUrl": "http://localhost:3743/", 
      "sslPort": 44326 
    } 
  }, 

The default HTTP port, which is shown in the preceding code, is set to 3743. As in the AddMvc middleware, we have specified a filter to use SSL for all incoming requests. It will automatically redirect to the HTTPS and use port 44326

To host ASP.NET Core on IIS, please refer to the following link. Once the website is up and running, the HTTPS binding can be added through the Site bindings options in IIS: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/index?tabs=aspnetcore2x

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.224.135