Asp.net MVC 5重定向到账户/登录

5

我正在学习ASP.NET MVC。我的MVC版本是5.2.2.0。

我在Employee控制器的Index()方法中附加了Authorize属性。

在Web.config文件中,我将authentication标签数据更改为以下内容:

<system.web>
    <authentication mode="Forms">
        <forms loginurl="~/Authentication/Login"></forms>
    </authentication>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
</system.web>

期望的是当访问localhost:port/Employee/Index时,用户应该被重定向到localhost:port/Authentication/Login

但实际上它却被重定向到了localhost:port/Account/Login

根据其他链接的情况,我尝试了以下方法:

1.添加

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
<add key="loginUrl" value="~/Authentication/Login" />
<add key="PreserveLoginUrl" value="true" />

将内容添加到Web.config的appSettings部分

2.将IIS 8匿名身份验证从指定用户更改为应用程序池标识

3.当上述两种方法都不起作用时,我将身份验证标签更改为

<authentication mode="Windows" />

但是没有一个有效。

编辑 不要执行我上面提到的1、2、3步骤。只需按照答案中提到的更改即可。

3个回答

7
问题在于默认情况下,OWIN中间件会配置为将cookie身份验证重定向到“/Account/Login”。
打开/AppStart/Startup.Auth.cs并编辑以下代码块以将其指向我们自己的URL:-
app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });            
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

1
你是指 Startup.cs 还是 Startup.Auth.cs?我猜想应该是 Startup.Auth.cs。 - Engineer
是的,它是Startup.Auth.cs文件。 - Engineer

1
也许这已经改变了。我正在学习ASP.NET 5(dnx451和MVC 6.0.0-rc1-final),在那里您必须在服务中定义登录的默认重定向地址:“ConfigureServices”方法而不是“Configure”方法。
public void ConfigureServices(IServiceCollection services)
    {
            services.AddIdentity<IdentityUser, IdentityRole>(configure =>
        {
            //add some requirements
            configure.User.RequireUniqueEmail = true;
            configure.Password.RequiredLength = 8;
            //define the default page if a call must be [Autorized]
            configure.Cookies.ApplicationCookie.LoginPath =  "/Auth/Login"; 
        })
        .AddEntityFrameworkStores<AuthContext>(); //use entity framework to store the user data
}

1
找了好一段时间了,谢谢! - Marcin Rybacki

0
在web.config中注释掉以下行,就不会自动跳转到“Account/Login”页面了。我在VS2015中测试过,效果很好。
需要注释的行:
<remove name="FormsAuthentication"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接