ASP.NET核心,更改默认重定向未授权

我试图重定向到ASP.NET MVC6中的另一个登录URL

我的帐户控制器登录方法有一个Route属性来更改URL。

 [HttpGet] [AllowAnonymous] [Route("login")] public IActionResult Login(string returnUrl = null) { this.ViewData["ReturnUrl"] = returnUrl; return this.View(); } 

当试图访问一个unathorized页面时,我被重定向到无效的URL,它应该只是/login但是我得到http://localhost/Account/Login?ReturnUrl=%2Fhome%2Findex

我已经配置了cookie身份validation路径,如下所示:

 services.Configure(opt => { opt.LoginPath = new PathString("/login"); }); 

我添加了一个默认filter,以确保默认情况下所有URL都需要身份validation。

 services.AddMvc( options => { options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())); }); 

我已经检查过url /login确实加载了登录页面,而/account/login没有按预期加载。

编辑:我按原样离开了路径,(除了更改默认控制器和操作)

 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Site}/{action=Site}/{id?}"); }); 

如果您在此处检查UseIdentity扩展方法,您会注意到它使用的是IdentityOptions而不是CookieAuthenticationOptions ,因此您必须配置IdentityOptions

 services.Configure(opt => { opt.Cookies.ApplicationCookie.LoginPath = new PathString("/login"); }); 

编辑

对于asp.net core 2.0:身份cookie选项不再是IdentityOptions的一部分。 检查mxmissile的答案 。

现在使用asp.net core 2.0 ,这已经变为:

 services.ConfigureApplicationCookie(options => options.LoginPath = "/Account/LogIn"); 

有关迁移到2.0的更多信息 。 有关从2.0迁移到2.1的更多信息 。

您可能还想尝试使用StatusCodePages

 app.UseStatusCodePages(async context => { var response = context.HttpContext.Response; if (response.StatusCode == (int)HttpStatusCode.Unauthorized || response.StatusCode == (int)HttpStatusCode.Forbidden) response.Redirect("/Account/Login"); }); 

更新:从dot net core 2.1.x开始,Identity是从SDK搭建的。 要共同签署@mxmissile答案,可以指定路径。 要实现技巧路径,请结合高级路由或重定向。 脚手架身份

我不会在一个真实的例子中推荐Serj Sagan解决方案。 这在开发时可以很好地工作,但是对于可能具有误导性的不同类型用户使用的真实应用程序。 让我们看看下面的场景

  1. 我经过身份validation使用过
  2. 我知道特定页面的url
  3. 我没有授权访问该页面

这意味着我将被重定向到登录页面,就好像我没有经过身份validation,但事实并非如此。 我会更多地使用mxmissile解决方案

个人我正在使用AddMvcCore,但是如果你使用razor视图和AddRazorPages你需要添加AddRazorViewEngine如果你使用剃刀页面

  services.AddMvcCore(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }) .AddRazorViewEngine() .AddAuthorization() .AddJsonFormatters();