为什么 ASP.NET Identity returns 401 而不是重定向到登录页面?

Why ASP.NET Identity returns 401 instead redirect to login page?

我正在尝试使用代码优先将 ASP NET Identity 添加到现有的 mvc5 项目中。 研究了new project,里面生成了VS,看了很多关于ASP.NET Identity的文章。 大多数情况下,我将代码从模板复制到我的项目中。我只是在 IdentityDbContext 上替换了 DBContext 并且几乎没有更改。表由 EF Migration 生成,并通过 UserManager 和 RoleManager 由 Seed 方法填充,因此,我认为,部分代码按预期工作。

但是,当我将 [Authorize] 添加到控制器(不是 WebApi,只是控制器),并尝试从控制器获取页面时,我遇到了一个问题 - 服务器 returns 401.0 错误,尽管选项设置为 LoginPath = new PathString("/Account/Login").

这是我的代码Startup.Auth.cs

namespace App
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(CwDb.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
        }
    }
}

这是我的 Startup.cs

[assembly: OwinStartupAttribute(typeof(CarWashApplication.Startup))]
namespace App
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            ConfigureAuth(app);
        }
    }
}

我只需要 login/pass 和 cookie 的简单身份验证,我不需要社交网络等的身份验证。

我哪里错了?如何像在 vs 生成的模板中那样获得重定向?

我找到了解决办法。我刚刚将 Microsoft.Owin.Host.SystemWeb 添加到项目中并且它起作用了。不幸的是,我所看到的文章中没有任何关于这个库的必要性的信息。