我目前正在关注Udemy中的.Net Core Angular 8教程。我可以在Postman中获取/发布请求,还可以使用sqlite作为数据库查看.db文件中发布的内容,并通过Db浏览器查看数据。一切似乎都很好,但是如果我不理解应用程序某些区域的情况,那一切都将一事无成。如果有人可以帮助我回答几个问题,我将不胜感激。
我的整个项目都在GitHub:https://github.com/cjtejada/ASP.NetCoreAngular8/tree/master/DatingApp.API
问题1:我具有以下控制器:
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IAuthRepository _repo;
private readonly IConfiguration _config;
public AuthController(IAuthRepository repo,IConfiguration config)
{
_repo = repo;
_config = config;
}
[HttpPost("register")]
public async Task<IactionResult> Register(UserForRegisterDto userForRegisterDto)
{
// validate request
userForRegisterDto.username = userForRegisterDto.username.ToLower();
if (await _repo.UserExists(userForRegisterDto.username))
return BadRequest("User already exists");
var userToCreate = new User
{
username = userForRegisterDto.username
};
var createdUser = await _repo.Register(userToCreate,userForRegisterDto.Password);
return StatusCode(201);
}
}
我知道,当客户端发出注册请求时,将调用register()方法,传入的用户名将从DTO userForRegisterDto设置用户名。之后,我们调用方法UserExists()来检查用户是否存在于我们的数据库中。
问题1: 仅使用接口IAuthRepository时,_repo如何知道方法UserExists()中的逻辑?我知道IAuthRepository和AuthRepository类以某种方式链接在一起,但在应用程序中未发生构造器DI的任何地方。我的怀疑是它与configure.services方法下的startup.cs中的这一行有关:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.getconnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors();
services.AddScoped<IAuthRepository,AuthRepository>(); //<---- This Line
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
};
});
}
将这两个“链接起来”后,便可以通过AuthRepository类访问UserExists()方法:
public class AuthRepository : IAuthRepository
{
private readonly DataContext _context;
public AuthRepository(DataContext context)
{
_context = context;
}
public async Task<User> Login(string username,string password)
{
}
private bool VerifyPasswordHash(string password,byte[] passwordHash,byte[] passwordSalt)
{
}
public async Task<User> Register(User user,string password)
{
byte[] passwordHash,passwordSalt;
CreatePasswordHash(password,out passwordHash,out passwordSalt);
user.PasswordHash = passwordHash;
user.PasswordSalt = passwordSalt;
await _context.Users.AddAsync(user);
await _context.SaveChangesAsync();
return user;
}
private void CreatePasswordHash(string password,out byte[] passwordHash,out byte[] passwordSalt)
{
}
public async Task<bool> UserExists(string username)
{
if (await _context.Users.AnyAsync(x => x.username == username))
return true;
return false;
}
}
我一直在阅读有关AddScoped方法及其作用的信息,但是我不清楚这是事实。任何关于它如何工作的澄清都很好。
问题2: 这个差不多是一样的。如果我们继续遵循请求的路径,我们将点击AuthRepository类中的register()方法。
问题2: 当我也无法在任何地方发现构造函数DI的任何实例时,此类如何访问DataContext _context的属性?
如果需要,这里是我的其余项目文件:
Startup.cs
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)
{
services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.getconnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors();
services.AddScoped<IAuthRepository,AuthRepository>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,ValidateAudience = false
};
});
}
// 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
{
//app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthentication();
app.UseMvc();
}
}
DataContext.cs
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base (options){}
public DbSet<Value> Values { get; set; }
public DbSet<User> Users { get; set; }
}
任何澄清和建议,我们将不胜感激。谢谢,一切。