简体   繁体   中英

How do you solve the error “could not load file or assembly 'microsoft aspnetcore razor runtime 3.1 1”,

I've posted this question before but being new I wanted to learn how to write a "proper" question (in case you've tried to help me and I didn't get back immediately, wanted to get it mostly right if not all hopefully I've got the hang of it)

This is just registration/login code whose purpose is self explanatory, the error am getting (could not load file or assembly 'microsoft aspnetcore razor runtime 3.1 1) happens in a service registration class in the AddControllers() method, I've tried adding the package specified in the error but it didn't work, I tried a few other similar packages but the result has been the same, when I build I get no errors or warnings but when the app runs I get the error, hope this is enough data to work with.

//controller class Login and registration
        [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
            public class IdentifyMe : Controller
            {
                private readonly IIdentify _identify;
        
                public IdentifyMe(IIdentify identifying)
                {
                    _identify = identifying;
                }
        
                [HttpGet(Api_Routes.Identity.Register)]
                public async Task<IActionResult> Register(UserRegistration register)
                {
                    if (!ModelState.IsValid)
                    {
                        return BadRequest(new Unauthenticated
                        {
                            Errors=ModelState.Values.SelectMany(x=>x.Errors.Select(xx=>xx.ErrorMessage))
                        });
                    }
        
        
                    var authresponce = await _identify.RegisterAsync(register.Email, register.Password, register.User_Name);
        
                    if (!authresponce.Success)
                    {
                        return BadRequest(new Unauthenticated
                        {
                            Errors = authresponce.Errors
                        });
                    }
                    return Ok(new Authenticated
                    {
                        Token = authresponce.Token
                    });
                }
        
        
        
                [HttpGet(Api_Routes.Identity.Login)]
                public async Task<IActionResult> LoginAsync(User_login login)
                {
                    var authresponce = await _identify.LoginAsync(login.Password, login.email);
        
                    if (!authresponce.Success)
                    {
                        return BadRequest(new Unauthenticated
                        {
                            Errors = authresponce.Errors
                        });
                    }
                    return Ok(new Authenticated
                    {
                        Token = authresponce.Token
                    });
                }
        
        
            }
        
        // service registration
        
        public class Dbinstaller : IInstaller
        {
            public void Cleanner(IConfiguration configuration, IServiceCollection services)
            {
                var jwt = new JWTsettings();
                configuration.Bind(nameof(jwt), jwt);
                services.AddSingleton(jwt);
        
                services.AddAuthentication(x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                    .AddJwtBearer(x =>
                    {
                        x.SaveToken = true;
                        var TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwt.Secret)),
                            ValidateIssuer = false,
                            ValidateAudience = false,
                            RequireExpirationTime = false,
                            ValidateLifetime = true
                        };
                    });
        
        
                services.AddSwaggerGen(x =>
                {
                    x.SwaggerDoc("v1", new OpenApiInfo { Title = "TXC API", Version = "v1" });
        
                    var security = new Dictionary<string, IEnumerable<string>>
                    {
                        {"Bearer", new string[0]}
                    };
        
                    x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                        { 
                         Description="JWT Authorization Header using the bearer scheme",
                         Name="Authorization",
                         In=ParameterLocation.Header,
                         Type=SecuritySchemeType.ApiKey
                        });
                    x.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {new OpenApiSecurityScheme{Reference=new OpenApiReference
                        {
                            Id="Bearer",
                            Type=ReferenceType.SecurityScheme
                        }
                        },new List<string>() }
                    });
                });
        
                
        
        
        
                services.AddDbContext<DataContext>(opt =>
                opt.UseSqlServer(configuration.GetConnectionString("TXC Connection")));
                services.AddIdentityCore<IdentityUser>();
            }
        }
        
        
        
        
            //service registration, specified error occurs in Add controllers()    
                 public class In_App_Componentes : IInstaller
                    {
                        public void Cleanner(IConfiguration configuration, IServiceCollection services)
                        {
                            services.AddControllers().AddNewtonsoftJson(p => p.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());
                            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
                            services.AddScoped<IX_Change, The_center>();
                            services.AddScoped<IIdentify, Identify>();
                        }
                    }
    
    //service implementation class
    public class Identify : IIdentify
        {
            private readonly UserManager<IdentityUser> _manager;
    
            private readonly JWTsettings jwtset;
    
    
    
            public Identify(UserManager<IdentityUser> userManager, JWTsettings jW)
            {
                _manager = userManager;
                jwtset = jW;
            }
    
           
    
            public async Task<Authentication_result> RegisterAsync(string email, string password, string Username)
            {
                var exists = _manager.FindByEmailAsync(email);
    
                if (exists != null)
                {
                    return new Authentication_result
                    {
                        Errors = new[] { "User with this email already exists" }
                    };
                }
    
                var newPerson = new IdentityUser
                {
                    Email = email,
                    UserName = Username
                };
    
                var Creation = await _manager.CreateAsync(newPerson, password);
    
                if (!Creation.Succeeded)
                {
                    return new Authentication_result
                    {
                        Errors = new[] { "Invalid user!" }
                    };
                }
    
                return Generate_Authentication_Result(newPerson);
            }
    
            public async Task<Authentication_result> LoginAsync(string email, string Password)
            {
                var user = await _manager.FindByEmailAsync(email);
    
                if (user == null)
                {
                    return new Authentication_result
                    {
                        Errors = new[] { "User does not exists" }
                    };
                }
    
                var validate_password = await _manager.CheckPasswordAsync(user, Password);
    
                if (!validate_password)
                {
                    return new Authentication_result
                    {
                        Errors = new[] { "" }
                    };
                }
    
                return Generate_Authentication_Result(user);
            }
    
            private Authentication_result Generate_Authentication_Result(IdentityUser newPerson)
            {
                var Tokenhandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes(jwtset.Secret);
                var TokenDescripter = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new[]
                   {
                       new Claim(JwtRegisteredClaimNames.Sub, newPerson.Email),
                       new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                       new Claim(JwtRegisteredClaimNames.Email, newPerson.Email),
                       new Claim("id",newPerson.Id)
    
                   }),
    
                    Expires = DateTime.UtcNow.AddHours(2),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
    
                var token = Tokenhandler.CreateToken(TokenDescripter);
    
                return new Authentication_result
                {
                    Success = true,
                    Token = Tokenhandler.WriteToken(token)
                };
            }
        }

Ciao, I tried to search Microsoft.AspNetCore.Razor.Runtime v. 3.1.1 on NuGet but I found only 2.2.0. I didn't found any reference to 3.1.1. Anyway, downgrading Microsoft.AspNetCore.Identity.UI to 3.1.0 should solve your problem as mentioned here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM