Advertisement

#2 Upgrade to Version 2.1

In this article we take the steps to upgrade our project from version 2.0 to version 2.1. These changes range from setting and enforcing the use of https for both our development environment as well as production to moving our common layout page to a different location. At the end we will also create a new npm script command to make it easier to start up our development server.

The information contained within this article, with a few additional items that might be relevant to your project, can be found here.

Updating the launch settings

  • WebUi
    • Properties
      • launchSettings.json

We are going to start by making some https related changes to our launch settings (a). The first change is to add an ssl port number under the iisSettings key and the second is to change the application url under the Development key from http to https. Depending on how you serve your application during development only one of these changes is going to matter.

launchSettings.json

{
    "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
            "applicationUrl": "http://localhost:50252/",
            "sslPort": 44385 <-- Pick a port
        }
    },
    "profiles": {
        "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
            }
        },
        "Development": {
            "commandName": "Project",
            "launchBrowser": true,
            "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "applicationUrl": "https://localhost:50253/" <-- Switch to https
        }
    }
}
(a) Updating our launch settings to use the specified ssl port number for iisexpress and changing the url from http to https in our development profile.

Updating our project file

  • WebUi
    • WebUi.csproj

The next thing on the agenda is to update our .csproj file. If you are using Visual Studio you can just right click on the project name in the solution explorer and use the context menu to select edit ProjectName.csproj option. If you are using some other editor the file is probably just displayed as any other that you can just click on. Once the file is open we just need to make the changes shown in (b).

WebUi.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>netcoreapp2.1</TargetFramework>
    </PropertyGroup>
    ...
    <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.2" />
        <PackageReference Include="Microsoft.AspNetCore.SpaServices" Version="2.1.1" />
    </ItemGroup>
    ...
</Project>
(b) The changes that we need to make to update our project. The version numbers are the current versions as of the time of the writing of this article.

Once the changes are made and file is saved a package restore is needed. Once again if you are using Visual Studio the restore should be performed automatically if it is not or you are not using Visual Studio you kick off a package restore yourself by using the dotnet restore command in our console. At end of this article will be the full csproj file for reference (c).

Updating Progam.cs

  • WebUi
    • Program.cs

Although not strictly required there are some changes that are recommended that we will make to our program.cs file. The simplest thing to do is just to copy and paste the code shown in (d) into your program.cs file.

Program.cs

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace WebUi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseDefaultServiceProvider(x => x.ValidateScopes = false);
    }
}
(d) The recommended code for the program.cs file in a new AspDotNet Core 2.1 application.

Updating Startup.cs

  • WebUi
    • Startup.cs

In our startup file there are a few things that we need to update. We start in our configure services method (e), by configuring the use of cookies within our application. This addition is in response to the EU General Data Protection Regulation (GDPR) passage and Microsoft's attempt to make it easier for developers to be in compliance with the regulation. You can read more about the GDPR from the information portal. Next we need to set the version of the framework that we are trying to use. You can read more about the motivation and effect of this change from this blog post.

Startup.cs

...
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
...

namespace WebUi
{
    public class Startup
    {
        ...
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        ...
    }
}
(e) Updating our configure services method.
Advertisement

Next up are the changes that we need to make to our configure method (f). Since never really used browser link I have chosen to just remove the line which references it. If you do want to use it you can install the BrowserLink nuget package. Next up is a call to enable the strict transport security header to our response if the application is running in production mode. We follow that by using the https redirection middleware to enforce the use of https and finally a call to the use cookie policy middleware to once again help use with the use of cookies within our application.

Startup.cs

...

namespace WebUi
{
    public class Startup
    {
        ...
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink(); <-- Remove
                ...
            }
            else
            {
                ...
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            ...
            app.UseCookiePolicy();
            ...
        }
    }
}
(f) Updating our configure method.

Just like with the csproj file you can find the full contents of the Startup.cs file at the end of this article (g).

Moving the layout page

  • WebUi
    • Pages
      • Shared
        • _Layout.cshtml
      • _Layout.cshtml

Although you do not have to it is probably nice to keep consistency between projects and since new projects will have the layout page under a shared folder we might as well move it for this project as well.

Starting the web server

  • WebUi
    • package.json

After making these changes would should probably startup the server and make sure that everything is still working as it should be. Since I am so used to invoking npm commands to make things easier we will add a script command to our package.json file (h).

package.json

{
    ...
    "scripts": {
        ...,
        "watch": "dotnet watch run --environment \"Development\""
    },
    ...
}
(h) Script command that will make it easier to startup the server.

Once that has been done we can invoke the command as shown (i).

Terminal

npm run watch
(i) The command used to start the server.

If everything has gone to planned we should not have an updated application that we should be able to view running in the browser once again.

Full WebUi.csproj file

WebUi.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>netcoreapp2.1</TargetFramework>
    </PropertyGroup>
    <PropertyGroup>
        <TypeScriptCompileBlocked>True</TypeScriptCompileBlocked>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.2" />
        <PackageReference Include="Microsoft.AspNetCore.SpaServices" Version="2.1.1" />
    </ItemGroup>
    <ItemGroup>
        <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.3" />
    </ItemGroup>
    <ItemGroup>
        <Folder Include="wwwroot\css\" />
        <Folder Include="wwwroot\images\" />
        <Folder Include="wwwroot\js\" />
        <Folder Include="wwwroot\lib\" />
    </ItemGroup>
</Project>
(c) The full csproj file.

Full Startup.cs file

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebUi.Infrastructure;

namespace WebUi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc();
        }
    }
}
(g) The full Startup.cs file.
Exciton Interactive LLC
Advertisement