gpt4 book ai didi

c# - 为什么 ASP.NET Identity 返回 401 而不是重定向到登录页面?

转载 作者:行者123 更新时间:2023-11-30 18:20:28 24 4
gpt4 key购买 nike

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

但是,当我将 [Authorize] 添加到 Controller(不是 WebApi,只是 Controller),并尝试从 Controller 获取页面时,我遇到了一个问题 - 服务器返回 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);
}
}
}

我只需要通过登录/密码和 cookie 进行简单的身份验证,我不需要通过社交网络等进行身份验证。

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

最佳答案

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

关于c# - 为什么 ASP.NET Identity 返回 401 而不是重定向到登录页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com