我正在尝试重定向到 ASP.NET MVC6 中的不同登录 url
我的账户控制器登录方法有一个Route
属性来改变url.
[HttpGet][允许匿名][路线(登录")]公共 IActionResult 登录(字符串 returnUrl = null){this.ViewData["ReturnUrl"] = returnUrl;返回 this.View();}
<块引用>
当尝试访问未经授权的页面时,我被重定向到无效的 url,它应该只是 /login
但我得到了http://localhost/Account/Login?ReturnUrl=%2Fhome%2Findex
我已经配置了cookie认证路径如下:
services.Configure(opt =>{opt.LoginPath = new PathString("/login");});
我添加了一个默认过滤器,以确保默认情况下所有 url 都需要身份验证.
services.AddMvc(选项=>{options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));});
我已经检查了 url /login
确实加载了登录页面,而 /account/login
没有,如预期的那样.
我已将路线保持原样(除了更改默认控制器和操作)
app.UseMvc(routes =>{路线.MapRoute(名称:默认",模板:{controller=Site}/{action=Site}/{id?}");});
如果勾选 UseIdentity
扩展方法 here 你会注意到它使用的是 IdentityOptions
而不是 CookieAuthenticationOptions
,所以相反,您必须配置 IdentityOptions
:
services.Configure(opt =>{opt.Cookies.ApplicationCookie.LoginPath = new PathString("/login");});
编辑
对于 asp.net core 2.0:身份 cookie 选项不再是 IdentityOptions 的一部分.检查 mxmissile 的答案.
I am attempting to redirect to a different login url in ASP.NET MVC6
My account controller login method has a Route
attribute to change the url.
[HttpGet]
[AllowAnonymous]
[Route("login")]
public IActionResult Login(string returnUrl = null)
{
this.ViewData["ReturnUrl"] = returnUrl;
return this.View();
}
When attempting to access an unathorized page, I am redirected to the invalid url, it should just be
/login
but instead I gethttp://localhost/Account/Login?ReturnUrl=%2Fhome%2Findex
I have configured the cookie authentication path as follows:
services.Configure<CookieAuthenticationOptions>(opt =>
{
opt.LoginPath = new PathString("/login");
});
I have added a default filter, to ensure that all urls require authentication by default.
services.AddMvc(
options =>
{
options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
});
I have checked that the url /login
does in fact load the login page, whilst /account/login
does not, as expected.
edit: I have left the routes as is, (apart from changing the default controller and action)
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Site}/{action=Site}/{id?}");
});
If you check UseIdentity
extension method here you will notice that it is using IdentityOptions
not CookieAuthenticationOptions
, so instead you must configure IdentityOptions
:
services.Configure<IdentityOptions>(opt =>
{
opt.Cookies.ApplicationCookie.LoginPath = new PathString("/login");
});
Edit
For asp.net core 2.0: Identity cookie options are no longer part of IdentityOptions. Check mxmissile's answer.
这篇关于ASP.NET 核心,更改未经授权的默认重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!