Can a class library have an App.config file?

后端 未结 7 988
别跟我提以往
别跟我提以往 2020-11-27 04:04

Here is what my solution is looking like at the moment:

\"enter

In the Tutomen

相关标签:
7条回答
  • 2020-11-27 05:00

    just use this common config to handle d.injection of services in class lib;

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<AppDBContext>(options =>
                {
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                        assembly => assembly.MigrationsAssembly(typeof(AppDBContext).Assembly.FullName));
                });
    
                services.AddScoped<IUsersRepository, UsersRepository>();
    
                services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader();
                }));
    
                // configure strongly typed settings objects
                var appSettingsSection = Configuration.GetSection("AppSettings");
                services.Configure<AppSettings>(appSettingsSection);
    
                // configure jwt authentication
                var appSettings = appSettingsSection.Get<AppSettings>();
                var key = Encoding.ASCII.GetBytes(appSettings.Secret);
                services.AddAuthentication(x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(x =>
                {
                    x.RequireHttpsMetadata = false;
                    x.SaveToken = true;
                    x.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
                app.UseCors("MyPolicy");
                app.UseHttpsRedirection();
                app.UseAuthentication();
                app.UseMvc();
    
            }
    

    appsettingjson file:

    {
          "Logging": {
            "LogLevel": {
              "Default": "Warning"
            }
          },
          "ConnectionStrings": {
            "DefaultConnection": "server=.;database=TestAPP;User ID=yener1;password=yener1;"
          },
          "AppSettings": {
            "Secret": "REPLACE THIS WITH YOUR OWN SECRET, IT CAN BE ANY STRING"
          },
          "AllowedHosts": "*"
    
    }
    

    //commentout

      public static class Hasher
        {
            public static string ToEncrypt<T>(this T value)
            {
                using (var sha256 = SHA256.Create())
                {
                    // Send a sample text to hash.  
                    var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(value.ToString()));
                    // Get the hashed string.  
                    return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                }
            }
        }
    public class AppDBContext : DbContext
    {
        public AppDBContext(DbContextOptions options)
            : base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
        }
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    
        public DbSet<Users> Users { get; set; }
    //BLL
        public class UsersRepository : IUsersRepository
        {
            private readonly AppDBContext _context;
            public UsersRepository(AppDBContext context)
            {
                _context = context;
            }
            public async Task<IEnumerable<Users>> GetUsers()
            {
                return await _context.Users.ToListAsync();
            }
    
    
    [AllowAnonymous]
            [HttpPost("authenticate")]
            public IActionResult Authenticate([FromBody]UserDto userDto)
            {
                var user = _userService.Authenticate(userDto.Username, userDto.Password);
    
                if (user == null)
                    return BadRequest("Username or password is incorrect");
    
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[] 
                    {
                        new Claim(ClaimTypes.Name, user.Id.ToString())
                    }),
                    Expires = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);
    
                // return basic user info (without password) and token to store client side
                return Ok(new {
                    Id = user.Id,
                    Username = user.Username,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Token = tokenString
                });
            }
    
    0 讨论(0)
提交回复
热议问题