我正在尝试重定向到ASP.NET MVC6中的其他登录URL
我的帐户控制器登录方法有一个Route
属性来更改网址。
[HttpGet]
[AllowAnonymous]
[Route("login")]
public IActionResult Login(string returnUrl = null)
{
this.ViewData["ReturnUrl"] = returnUrl;
return this.View();
}
当尝试访问未经过处理的页面时,我被重定向到无效的网址,它应该只是
/login
而是我得到的 的http://localhost/Account/Login?ReturnUrl=%2Fhome%2Findex
我已按如下方式配置了cookie身份验证路径:
services.Configure<CookieAuthenticationOptions>(opt =>
{
opt.LoginPath = new PathString("/login");
});
我添加了默认过滤器,以确保默认情况下所有网址都需要进行身份验证。
services.AddMvc(
options =>
{
options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
});
我已检查过网址/login
确实加载了登录页面,而/account/login
没有按预期加载。
编辑:我按原样离开了路线,(除了更改默认控制器和操作)
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Site}/{action=Site}/{id?}");
});
答案 0 :(得分:33)
现在asp.net core 2.0
退出,已更改为:
services.ConfigureApplicationCookie(options => options.LoginPath = "/Account/LogIn");
有关migrating to 2.0 here的更多信息。并且even more information从2.0迁移到2.1。
答案 1 :(得分:13)
如果您检查UseIdentity
扩展方法here,您会发现它使用IdentityOptions
而不是CookieAuthenticationOptions
,因此您必须配置IdentityOptions
:
services.Configure<IdentityOptions>(opt =>
{
opt.Cookies.ApplicationCookie.LoginPath = new PathString("/login");
});
修改强>
对于asp.net核心2.0: 标识cookie选项不再是IdentityOptions的一部分。检查mxmissile的answer。
答案 2 :(得分:6)
更新: 从点网核心2.1.x开始,身份从SDK扩展。 要共同签名@mxmissile答案,可以指定路径。要开启特技路径,请结合使用高级路由或重定向。Scaffold Identity
答案 3 :(得分:4)
您可能还想尝试使用StatusCodePages
:
app.UseStatusCodePages(async context => {
var response = context.HttpContext.Response;
if (response.StatusCode == (int)HttpStatusCode.Unauthorized ||
response.StatusCode == (int)HttpStatusCode.Forbidden)
response.Redirect("/Error/Unauthorized");
});
答案 4 :(得分:1)
在实际示例中,我不会推荐Serj Sagan解决方案。这在开发时会非常有效,但对于可能引起误导的不同类型用户使用的实际应用程序而言。让我们看看下面的情况
这意味着我将被重定向到登录页面,就像我没有通过身份验证一样(不是这种情况)。我会更多地使用mxmissile解决方案
我个人使用的是AddMvcCore,但是如果使用的是剃刀视图,则需要添加AddRazorViewEngine,如果使用的是剃刀页面,则需要添加AddRazorPages
services.AddMvcCore(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddRazorViewEngine()
.AddAuthorization()
.AddJsonFormatters();
答案 5 :(得分:1)
自asp.net core 2.0
起,如果您使用不带身份的Cookie:
app.UseAuthentication();
// If you don't want the cookie to be automatically authenticated and assigned HttpContext.User,
// remove the CookieAuthenticationDefaults.AuthenticationScheme parameter passed to AddAuthentication.
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/LogIn";
options.LogoutPath = "/Account/LogOff";
});
答案 6 :(得分:1)
添加身份验证服务时,尤其是在使用cookie身份验证方案时,您需要在startup.cs中对其进行配置。
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/login");
});
这就是我解决问题的方式,您应该尝试一下...它一定会为您服务