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.
[ASP.NET Core][EntityFramework Core] Update from .NET 5 to .NET 6
[ASP.NET Core][Entity Framework Core][Npgsql] Try code first & DB first
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}; |
appsettings.json
...
"ConnectionStrings": {
"BookShelf": "sample_strings"
},
...
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();
...
[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();
...
- NLogBuilder.ConfigureNLog Method (String)
- ASP0011: Suggest using builder.Logging over Host.ConfigureLogging or WebHost.ConfigureLogging - Microsoft Learn
UseEndpoints
I can remove "app.UseEndpoints".
[From] Program.cs
...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
...
[To] Program.cs
...
app.MapControllers();
...
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();
});
...
[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();
});
...
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);
}
...
}
[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);
}
...
}
Top comments (0)