By using this site, you acknowledge that you have read and understand our Cookie policy, Privacy policy and Terms .
close

Migrating from ASP.NET Core 1.x to 2.0 is not an easy job especially if you have customized Identity and used customized authentication. This post summarizes the issues and errors I have experienced and their resolutions when upgrading my project. Hopefully it can save you sometime if you are doing the same.

Official Migration Guides

Please refer to the following official posts for general migration strategies and steps:

Migrating from ASP.NET Core 1.x to ASP.NET Core 2.0

Migrating Authentication and Identity to ASP.NET Core 2.0

[Draft] Auth 2.0 Migration announcement

Navigation Properties for IdentityUser<TKey>

Navigation properties: Roles, Claims and Logins have been removed from IdentityUser<TKey> class.

To add them back, you need to create your own user class , for example,

public class ApplicationUser : IdentityUser<int>

And then add the following attributes.

#region  asp.net core 2.0 support

/// <summary>
/// Navigation property for the roles this user belongs to.
/// </summary>
public virtual ICollection<IdentityUserRole<int>> Roles { get; } = new List<IdentityUserRole<int>>();

/// <summary>
/// Navigation property for the claims this user possesses.
/// </summary>
public virtual ICollection<IdentityUserClaim<int>> Claims { get; } = new List<IdentityUserClaim<int>>();

/// <summary>
/// Navigation property for this users login accounts.
/// </summary>
public virtual ICollection<IdentityUserLogin<int>> Logins { get; } = new List<IdentityUserLogin<int>>();

#endregion

To prevent duplicate foreign keys when running EF Core migrations, you can add the following to your IdentityDbContext class:

protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            …

           #region  asp.net core 2.0 support
            builder.Entity<ApplicationUser>()
                .HasMany(e => e.Claims)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Cascade);

           builder.Entity<ApplicationUser>()
                .HasMany(e => e.Logins)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Cascade);

           builder.Entity<ApplicationUser>()
                .HasMany(e => e.Roles)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Cascade);

            #endregion

Navigation Properties for IdentityRole<TKey>

Similar to the user class, navigation property Claims and Users have also been removed from IdentityRole<TKey> class. To add them back, create a ApplicationRoleClaim class:

public class ApplicationRoleClaim : IdentityRoleClaim<int>
     {
         public virtual ApplicationRole ApplicationRole { get; set; }
     }

Remember to change int to your own primary key type.

In your own customized IdentityRole<TKey> class, add the following code:

public class ApplicationRole : IdentityRole<int>
  {

        #region  asp.net core 2.0 support
         /// <summary>
         /// Navigation property for the users in this role.
         /// </summary>
         public virtual ICollection<IdentityUser<int>> Users { get; } = new List<IdentityUser<int>>();

        /// <summary>
         /// Navigation property for the claims this role possesses.
         /// </summary>
         public virtual ICollection<ApplicationRoleClaim> Claims { get; } = new List<ApplicationRoleClaim>();
         #endregion
     }

And then add the following code into your customized IdentityDbContext to prevent duplicate foreign key:

builder.Entity<ApplicationRoleClaim>()
                 .HasOne(pt => pt.ApplicationRole)
                 .WithMany(t => t.Claims)
                 .HasForeignKey(pt => pt.RoleId);

Error CS0023 Operator '!' cannot be applied to operand of type 'AuthorizationResult'

In one of my API controllers, I got the above error when building my project while it was working well with .net core SDK 1.x.

public async Task<IActionResult> GetUserById(int id)
         {
             if (!await authorizationService.AuthorizeAsync(this.User, id, ApplicationAuthorizationPolicies.ViewUserByUserIdPolicy))
                 return new ChallengeResult();

Change the code to:

if (!(await authorizationService.AuthorizeAsync(this.User, id, ApplicationAuthorizationPolicies.ViewUserByUserIdPolicy)).Succeeded)
                 return new ChallengeResult();

The change is required because in 1.x, IAuthorizationService is defined as:

public interface IAuthorizationService

{

Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements);

Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName);

}

In 2.0. it is changed to:
    public interface IAuthorizationService
    {
        Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements);
        Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName);
    }

An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (A key cannot be configured on 'ApplicationUser' because it is a derived type. The key must be configured on root type 'IdentityUser<int>'. If you did not intend for 'IdentityUser<int>' to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model.

The error itself is self-explaining. I have defined the following attribute in ApplicationRole class:

public virtual ICollection<IdentityUser<int>> Users { get; } = new List<IdentityUser<int>>();

While it should be changed to:

public virtual ICollection<ApplicationUser> Users { get; } = new List<ApplicationUser>();

Options.ClientId must be provided Parameter name: ClientId

Ensure you have configured all the required attributes for OIDC authentication.

services.AddAuthentication(options =>
             {
                 options.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme;
                 options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                 options.DefaultSignInScheme = OpenIdConnectDefaults.AuthenticationScheme;
             }).AddOpenIdConnect(options =>
             {
                 options.Authority = Configuration["auth:oidc:authority"];
                 options.ClientId = Configuration["auth:oidc:clientid"];

                 options.SaveTokens = true;
                 // for development, disable https requirement
                 options.RequireHttpsMetadata = false;
             });

If you have experienced more issues, please post here and we can discuss and resolve together.

info Last modified by Raymond at 4 months ago * This page is subject to Site terms.

info About author

More from Kontext

local_offer asp.net core 2 local_offer asp.net core local_offer dotnetcore local_offer open-banking

visibility 194
thumb_up 0
access_time 12 months ago

I’ve just started an asp.net core 2.2 based implementation for Australia Consumer Data Standards (published by Data 61). Opening Banking initiative will follow these standards. The purpose is to help you to get familiar with these standards, especially the APIs that need to be implemented. ...

open_in_new View

local_offer .net core local_offer lite-log

visibility 1783
thumb_up 0
access_time 2 years ago

After upgrading to ASP.NET Core 2.1 (.NET Core SDK 2.1.301), you may encounter the following error about encoding: System.ArgumentException &nbsp;&nbsp; HResult=0x80070057 &nbsp;&nbsp; Message='Cyrillic' is not a supported encoding name. For information on defining a cus...

open_in_new View

local_offer .net core local_offer entity-framework

visibility 14751
thumb_up 0
access_time 2 years ago

SQLite is a self-contained and embedded SQL database engine. In .NET Core, Entity Framework Core provides APIs to work with SQLite. This page provides sample code to create a SQLite database using package Microsoft.EntityFrameworkCore.Sqlite . Create sample project ...

open_in_new View

local_offer asp.net core 2 local_offer .net core

visibility 1683
thumb_up 0
access_time 2 years ago

In .NET Core 2.x, Windows Forms or WPF are not implemented since they are based on GDI+ and DirectX respectively in Windows. In .NET Core 3.0, there is plan to add Desktop Packs which includes UWP. WPF and Windows Forms. However, they will still be Windows-only. In .NET Core applications, you may...

open_in_new View

comment Comments (2)

comment Add comment

Please log in or register to comment. account_circle Log in person_add Register
account_circle Raymond

@Michael

https://github.com/aspnet/Identity/blob/dev/src/Microsoft.Extensions.Identity.Core/RoleManager.cs

The default query doesn’t include property Users as it is extended by us. Thus, you can write your own Linq query to use entity framework core extension method Include(r=>r.Users) to ensure Users are also loaded.

 In this way, the query generated will be a join SQL.



format_quote

person Michael access_time 3 years ago
Re:Migrating from ASP.NET Core 1.x to ASP.NET Core 2.0

Hello, I've followed your suggestions above but still can't get out how many users that are assigned to a Role. I get: System.Data.SqlClient.SqlException: 'Invalid column name 'ApplicationRoleId'.' when I'm executing following: model = roleManager.Roles.Select(r => new ApplicationRoleListViewModel { Id = r.Id, Name = r.Name, NumberOfUsers = r.Users.Count() }).ToList(); Do you have some ideas on what I have done wrong? Thanks, Michael.
reply Reply
account_circle Michael
Hello, I've followed your suggestions above but still can't get out how many users that are assigned to a Role. I get: System.Data.SqlClient.SqlException: 'Invalid column name 'ApplicationRoleId'.' when I'm executing following: model = roleManager.Roles.Select(r => new ApplicationRoleListViewModel { Id = r.Id, Name = r.Name, NumberOfUsers = r.Users.Count() }).ToList(); Do you have some ideas on what I have done wrong? Thanks, Michael.
reply Reply
Kontext Column

Kontext Column

Created for everyone to publish data, programming and cloud related articles. Follow three steps to create your columns.

Learn more arrow_forward
info Follow us on Twitter to get the latest article updates. Follow us