Home > other >  Not able to scaffold a controller in ASP.NET 6 Core Web API
Not able to scaffold a controller in ASP.NET 6 Core Web API

Time:01-03

I'm trying to scaffold controller for Entity Framework Core using ASP.NET Core Web API .NET 6.0. Everything builds and I can add migrations and update database. When I try to scaffold controller I get this error..

enter image description here

This is my Startup

using System;
using System.Net;
using System.Text;
using AutoMapper;
using Kasica.API.Business.Interfaces;
using Kasica.API.Business.Interfaces.External;
using Kasica.API.Business.Interfaces.Repositories;
using Kasica.API.Business.Services;
using Kasica.API.Business.Services.External;
using Kasica.API.Common.Entities;
using Kasica.API.Data;
using Kasica.API.Data.Extensions;
using Kasica.API.Data.Repositories;
using Kasica.API.Filters;
using Kasica.API.Helpers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;

namespace Kasica.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //konfiguracija identity 
            IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
            {
                opt.Password.RequireDigit = false;
                opt.Password.RequiredLength = 6;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase = false;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores<DataContext>();
            builder.AddRoleValidator<RoleValidator<IdentityRole>>();
            builder.AddRoleManager<RoleManager<IdentityRole>>();
            builder.AddSignInManager<SignInManager<User>>();
            builder.AddTokenProvider<DataProtectorTokenProvider<User>>(TokenOptions.DefaultProvider);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });

            services.AddControllers()
                .AddNewtonsoftJson(opt =>
                {
                    opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                });


            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Kasica API",
                    Description = "A simple example ASP.NET Core Web API",
                    //TermsOfService = new Uri("https://example.com/terms"),
                    //Contact = new OpenApiContact
                    //{
                    //    Name = "Shayne Boyer",
                    //    Email = string.Empty,
                    //    Url = new Uri("https://twitter.com/spboyer"),
                    //},
                    //License = new OpenApiLicense
                    //{
                    //    Name = "Use under LICX",
                    //    Url = new Uri("https://example.com/license"),
                    //}
                });

            });

            //extension u data layeru kako ne bi trebali imati entity framework referenciran od API layera
            services.AddDataAccessServices(Configuration.GetConnectionString("KasicaConnection"));
            services.AddCors();
            //services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());      //radi i ovo samo ovako
            services.AddAutoMapper(cfg => cfg.AddProfile<AutoMaperProfiles>(),
                               AppDomain.CurrentDomain.GetAssemblies());
            services.AddScoped<IAuthRepository, AuthRepository>();
            services.AddScoped<IAuthService, AuthService>();
            services.AddScoped<IErrorRepository, ErrorRepository>();
            services.AddScoped<IErrorService, ErrorService>();
            services.AddScoped<IUserRepository, UserRepository>();
            services.AddScoped<IUserService, UserService>();
            services.AddScoped<IEmailService, EmailService>();
            services.AddScoped<IKlijentRepository, KlijentRepository>();
            services.AddScoped<IKlijentService, KlijentService>();
            services.AddScoped<LogUserActivity>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            //else
            //{
            app.UseExceptionHandler(builder =>              //globalno exception handlanje
            {
                builder.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                            //context.Response.AddApplicationError(error.Error.Message);        //neću koristiti errore u headeru zbog problema sa encodingom cro znakova
                            await context.Response.WriteAsync(error.Error.Message);
                    }
                });
            });
            //}

            //app.UseHttpsRedirection();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.)
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                //c.RoutePrefix = string.Empty;
            });

            app.UseRouting();

            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

I have only one reference to Microsoft.AspNetCore.Identity enter image description here

I tried unistall and install all packages but nothigs works, I have no idea what to try next.

EDIT

I use SignInManager in referenced project "Data" layer and temporarly removed and used UserManager for check password...(I see SignInManager class in startup is using namespase "Microsoft.AspNetCore.Identity" but I don't know from what package, and in Data project i need to install Microsoft.AspNetCore.Identity package 2.2.0 if I want to use it!!!!???) Without reference to "Microsoft.AspNetCore.Identity" package 2.2.0 now the error is different but still can't fix it.

enter image description here

CodePudding user response:

Remove the Microsoft.AspnetCore.Identity package, it is no longer needed.

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-6.0&tabs=visual-studio

CodePudding user response:

Based on this article https://docs.microsoft.com/hr-hr/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli there was a problem creating DataContext at design time. I added this class and now scaffolding is working.


   public class DataContextFactory : IDesignTimeDbContextFactory<DataContext>
    {
        public DataContext CreateDbContext(string[] args)
        {
            var configuration = new ConfigurationBuilder()
             .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
             .AddJsonFile("appsettings.json")
             .Build();

            var optionsBuilder = new DbContextOptionsBuilder<DataContext>();
            optionsBuilder.UseSqlServer(configuration.GetConnectionString("KasicaConnection"));

            return new DataContext(optionsBuilder.Options);
        }
    }
  • Related