0

I am trying to implement IdentityFramework in my .NET Core 6 Web API Application.

Following is my settings.

public class ApplicationUser : IdentityUser<int>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

My connection string is :

  "ConnectionStrings": {
    "connectionString": "Server=DESKTOP-HO7FAAD\\SQLEXPRESS; Database=AviaryDB; Trusted_Connection=True; MultipleActiveResultSets=true;"
  }

Program.cs

builder.Services.AddIdentity<ApplicationUser, IdentityRole<int>>()
    .AddEntityFrameworkStores<ApplicationDBContext>()
    .AddDefaultTokenProviders();

builder.Services.AddDbContext<ApplicationDBContext>(db => db.UseSqlServer(builder.Configuration.GetConnectionString("connectionString")));

ApplicationDBContext.cs

public class ApplicationDBContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int>
    {
        public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
        {

        }

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

            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
            builder.Entity<ApplicationUser>(entity =>
            {
                entity.Property(p => p.Id).ValueGeneratedOnAdd();
                entity.Property(p => p.FirstName).HasMaxLength(150);
                entity.Property(p => p.LastName).HasMaxLength(150);
                entity.ToTable(name: "Users");
            });

            builder.Entity<IdentityRole<int>>(entity =>
            {
                entity.Property(p => p.Id).ValueGeneratedOnAdd();
                entity.ToTable(name: "Roles");
            });
            builder.Entity<IdentityUserRole<int>>(entity =>
            {
                entity.ToTable("UserRoles");
                //in case you chagned the TKey type
                entity.HasKey(key => new { key.UserId, key.RoleId });
            });

            builder.Entity<IdentityUserClaim<int>>(entity =>
            {
                entity.ToTable("UserClaims");
            });

            builder.Entity<IdentityUserLogin<int>>(entity =>
            {
                entity.ToTable("UserLogins");
                //in case you chagned the TKey type
                entity.HasKey(key => new { key.ProviderKey, key.LoginProvider });       
            });

            builder.Entity<IdentityRoleClaim<int>>(entity =>
            {
                entity.ToTable("RoleClaims");

            });

            builder.Entity<IdentityUserToken<int>>(entity =>
            {
                entity.ToTable("UserTokens");
                //in case you chagned the TKey type
                entity.HasKey(key => new { key.UserId, key.LoginProvider, key.Name });
            });
        }
    }

AccountController.cs

public class AccountController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;
        public AccountController(
            UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("register")]
        public async Task<ActionResult> Register([FromBody] RegisterModel model)
        {
            try
            {
                var userExists = await _userManager.FindByNameAsync(model.Username);
                if (userExists != null)
                    return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User already exists!" });

                ApplicationUser user = new()
                {
                    Email = model.Email,
                    SecurityStamp = Guid.NewGuid().ToString(),
                    UserName = model.Username,
                };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (!result.Succeeded)
                    return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User creation failed! Please check user details and try again." });

                return Ok("User created successfully!");
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
    }

And I am getting the following error. Can anyone guide me what I am doing wrong?

enter image description here

Usman Khalid
  • 3,032
  • 9
  • 41
  • 66
  • Does this answer your question? [Cannot Connect to Server - A network-related or instance-specific error](https://stackoverflow.com/questions/18060667/cannot-connect-to-server-a-network-related-or-instance-specific-error) – Ryan Wilson Jul 18 '22 at 19:49
  • No it did not solve the issue – Usman Khalid Jul 18 '22 at 20:05
  • I find it hard to believe you tried every possible answer in that post in less than 15 minutes. – Ryan Wilson Jul 18 '22 at 20:07
  • Most of the people are suggesting the same solution, i.e. enabling the TCP/IP. Others are suggesting to check sql server service is running. I have checked all. – Usman Khalid Jul 18 '22 at 20:08
  • I got it fixed, the problem was my Visual Studio was running the project from Docker and my sql server was outside of docker. – Usman Khalid Jul 19 '22 at 18:05

0 Answers0