DEV Community

Masui Masanori
Masui Masanori

Posted on

[ASP.NET Core][EntityFramework Core] Update from .NET 6 to .NET 8

Intro

This time, I will try ASP.NET Core Identity sign-in again.
I will upgrade my ASP.NET Core project.

As of 2024-11-17, the stable version of Npgsql.EntityFrameworkCore.PostgreSQL for .NET 9 has not yet been released, so I will upgrade the project to .NET 8.

Environments

  • .NET ver.8.0.404
  • Microsoft.EntityFrameworkCore ver.8.0.11
  • Npgsql.EntityFrameworkCore.PostgreSQL ver.8.0.10
  • NLog.Web.AspNetCore ver.5.3.14
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore ver.8.0.11
  • Microsoft.AspNetCore.Authentication.JwtBearer ver.8.0.11
  • Microsoft.EntityFrameworkCore.Design ver.8.0.11

Getting environment variables

I can use appsettings.json as an external config file.
But because I don't want to write secrets threre(ex. database connection strings), so I set them as Windows environment variables.

For example, if I set an environment variable as shown below, the application will replace the value of "ConnectionStrings:BookShelf" with the value of the environment variable at runtime.

Name Value
ConnectionStrings__BookShelf Host=localhost;Port=5432;Database=book_shelf;Username={User Name};Password={Password};

Image description

appsettings.json

...
  "ConnectionStrings": {
    "BookShelf": "sample_strings"
  },
...
Enter fullscreen mode Exit fullscreen mode

Upgrading the project

Most program code will work without modification.
However, some program code generates deprecation warnings or just can be simplified, so I will update them.

NLog(Logging)

"NLogBuilder.ConfigureNLog" is marked obsolete and "builder.Host.ConfigureLogging" isn't recommended.

[From] Program.cs

...
var logger = NLogBuilder.ConfigureNLog("Nlog.config").GetCurrentClassLogger();
try
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Host.ConfigureLogging(logging =>
    {
        logging.ClearProviders();
        logging.SetMinimumLevel(LogLevel.Trace);
    })
    .UseNLog();
...
Enter fullscreen mode Exit fullscreen mode

[To] Program.cs

...
var logger = LogManager.Setup().LoadConfigurationFromFile("Nlog.config").GetCurrentClassLogger();
try
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Logging.ClearProviders();
    builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
    builder.Host.UseNLog();
...
Enter fullscreen mode Exit fullscreen mode

UseEndpoints

I can remove "app.UseEndpoints".

[From] Program.cs

...
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
...
Enter fullscreen mode Exit fullscreen mode

[To] Program.cs

...
    app.MapControllers();
...
Enter fullscreen mode Exit fullscreen mode

HttpContext.Request.Headers.Add

To avoid duplicate the key, I change the method from "Add" to "Append".

[From] Program.cs

...
    app.Use(async (context, next) =>
    {
        var token = context.Session.GetString("user-token");
        if(string.IsNullOrEmpty(token) == false)
        {            
            context.Request.Headers.Add("Authorization", $"Bearer {token}");
        }
        await next();
    });
...
Enter fullscreen mode Exit fullscreen mode

[To] Program.cs

...
    app.Use(async (context, next) =>
    {
        var token = context.Session.GetString("user-token");
        if(string.IsNullOrEmpty(token) == false)
        {            
            context.Request.Headers.Append("Authorization", $"Bearer {token}");
        }
        await next();
    });
...
Enter fullscreen mode Exit fullscreen mode

Primary constructor

Because Most constructors simply assign instances to member variables, so they can be simplified with a primary constructor.

[From] UserController.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UpgradeProjectSample.Apps;
using UpgradeProjectSample.Users;
using UpgradeProjectSample.Users.Dto;

namespace UpgradeProjectSample.Controllers;
public class UserController: Controller
{
    private readonly IApplicationUserService userService;
    public UserController(IApplicationUserService userService)
    {
        this.userService = userService;
    }
    [AllowAnonymous]
    [HttpPost]
    [Route("/user/signin")]
    public async Task<UserActionResult> Signin([FromBody] SigninValue value)
    {
        if (value == null)
        {
            return ActionResultFactory.GetFailed("Failed getting sign in values");
        }
        return await userService.SigninAsync(value, HttpContext.Session);
    }
...
}
Enter fullscreen mode Exit fullscreen mode

[To] UserController.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UpgradeProjectSample.Apps;
using UpgradeProjectSample.Users;
using UpgradeProjectSample.Users.Dto;

namespace UpgradeProjectSample.Controllers;
public class UserController(IApplicationUserService userService) : Controller
{
    [AllowAnonymous]
    [HttpPost]
    [Route("/user/signin")]
    public async Task<UserActionResult> Signin([FromBody] SigninValue value)
    {
        if (value == null)
        {
            return ActionResultFactory.GetFailed("Failed getting sign in values");
        }
        return await userService.SigninAsync(value, HttpContext.Session);
    }
...
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)