正如标题所述,我想在.NET Core 2.1中实现某种授权,但是在学习他们的教程时遇到了麻烦。我已经设置了Startup.cs文件
public void ConfigureServices(IServiceCollection services)
{
string connection = Configuration.GetConnectionString("DefaultConnection");
if (_currentEnvironment.IsDevelopment())
services.AddDbContext<PagesContext>(options => options.UseSqlServer(connection), ServiceLifetime.Singleton);
else
services.AddDbContext<PagesContext>(options => options.UseMySql(connection), ServiceLifetime.Singleton);
services.AddIdentity<User, IdentityRole>(opts=>
{
opts.Password.RequireDigit = false;
opts.Password.RequiredLength = 8;
opts.Password.RequireLowercase = false;
opts.Password.RequireNonAlphanumeric = false;
opts.Password.RequireUppercase = false;
opts.User.AllowedUserNameCharacters = null;
}).AddEntityFrameworkStores<PagesContext>()
.AddDefaultTokenProviders();
services.AddSingleton<IStringLocalizerFactory, EFStringLocalizerFactory>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("en-GB"),
new CultureInfo("en"),
new CultureInfo("ru-RU"),
new CultureInfo("ru"),
new CultureInfo("uk-UA"),
new CultureInfo("ua")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("ru-RU"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(
routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
}
);
我有HomeController.cs文件,其中包含以下内容:
[HttpGet]
public async Task<IActionResult> Index()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
if (user != null)
{
if (await _userManager.IsInRoleAsync(user, "Admin"))
{
return LocalRedirectPermanent("/Admin/Index");
}
else if (await _userManager.IsInRoleAsync(user, "Carrier"))
{
return LocalRedirectPermanent("/Carrier/Index");
}
return LocalRedirectPermanent("/Passenger/Index");
}
Page indexPage = db.Page.Include(u => u.Title).Include(u => u.Description).FirstOrDefault(p => p.Tag == "main_page");
return View();
}
从我要检测的代码可以看出,如果用户已登录-显示相应的页面。如果不是-页面,则启用登录过程。但是,当使用身份验证时,默认路由将被忽略。如果从Visual Studio启动此程序,它将导航至/ Account / AccessDenied?ReturnUrl =%2FPassenger%2FIndex,而不是/ Home / Index。我该如何覆盖呢?
答案 0 :(得分:0)
我找到了。看起来,这不是.NET Core的错。它基于标题。
在我的情况下,LocalRedirectPermanent("/Admin/Index")
被多次调用,因此,它绕过了“ / Home / Index”而自动被称为“ / Admin / Index”。我认为,这是由于this造成的。因此,我已经通过以下方式在浏览器(Firefox)中进行了修复:重置历史记录(窗体,Cookie等)并在Visual Studio Build-> Rebuild Solution中执行。然后它又开始工作了。希望这对某人有所帮助