0

我正在尝试使用 ASP.NET Core Web API .NET 6.0 为 Entity Framework Core 搭建控制器。一切都建立起来了,我可以添加迁移和更新数据库。当我尝试搭建控制器时,出现此错误..

在此处输入图像描述

这是我的启动

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();
            });
        }
    }
}

我只有一个对 Microsoft.AspNetCore.Identity 的引用 在此处输入图像描述

我尝试 unistall 并安装所有软件包但 nothigs 工作,我不知道接下来要尝试什么。

编辑

我在引用的项目“数据”层中使用 SignInManager 并暂时删除并使用 UserManager 来检查密码...(我看到启动时的 SignInManager 类正在使用命名空间“Microsoft.AspNetCore.Identity”,但我不知道来自哪个包,并且在数据项目中,如果我想使用它,我需要安装 Microsoft.AspNetCore.Identity 包 2.2.0!!!!???)不参考“Microsoft.AspNetCore.Identity”包 2.2.0 现在错误有所不同,但仍然无法修复它。

在此处输入图像描述

4

2 回答 2

0

删除 Microsoft.AspnetCore.Identity 包,不再需要它。

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

于 2021-12-29T14:42:37.647 回答
0

根据这篇文章https://docs.microsoft.com/hr-hr/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli 在设计时创建 DataContext 时出现问题。我添加了这个类,现在脚手架正在工作。


   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);
        }
    }
于 2022-01-02T20:05:12.223 回答