c# - Cookie 身份验证和 Asp Net Core 2.0 迁移

标签 c# asp.net-mvc cookies asp.net-core migration

我找不到将应用程序从 aspnet core 1.1 迁移到使用 cookie 身份验证的 2.0 的方法。

我已经知道的最有用的资源是:

不幸的是,我仍然卡住了。以下是我的做法:
在 Startup.cs ConfigureServices(IServiceCollection services)我有:

services.AddSingleton<IConfigureNamedOptions<CookieAuthenticationOptions>, CookieAuthenticationOptionsSetup>();

及以后:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();

CookieAuthenticationOptionsSetup类(class)工具IConfigureNamedOptions并设置 options.Cookie.Name = "test"Configure里面方法。 我尝试手动创建 Name 属性并将其设置为“Cookies”。

如果我尝试在 Startup.cs 中使用 lambda 表达式更改 cookie 的名称 AddCookie方法,它按预期工作。 但如果我不这样做,CookieAuthenticationOptionsSetup从不使用,并使用默认的 cookie 名称 (.AspNetCore.Cookies)。

我错过了什么?

最佳答案

AddCookie() 默认调用 AuthenticationBuilder.AddScheme .从那里,我们可以了解如果您将选项传递给 AddCookie,这些选项将如何理想地注册。调用:

Services.Configure(authenticationScheme, configureOptions);

那么让我们来看看如何Services.Configure使用命名选项。什么ultimately gets registered在服务集合上是 IConfigureOptions<CookieAuthenticationOptions>> .

所以我猜这就是稍后通过 DI 解析选项时要查找的确切类型。事实上,that is the exact type OptionsFactory 正在请求OptionsMonitor 正在使用这是requested by the authentication handler .

所以,tl;dr:您将自定义配置注册为错误的类型。您应该将其注册为 IConfigureOptions<> :

services.AddSingleton<IConfigureOptions<CookieAuthenticationOptions>, CookieAuthenticationOptionsSetup>();

当然要注意你的 CookieAuthenticationOptionsSetup需要实现 IConfigureNamedOptions 正确回应Configure使用您的方案名称 ( CookieAuthenticationDefaults.AuthenticationScheme) 调用。

关于c# - Cookie 身份验证和 Asp Net Core 2.0 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45770419/

相关文章:

c# - 坐在窗口asp.net mvc时添加实体后发生StackOverflowException

c# - IEnumerable<string> 到 SelectList,没有选择值

asp.net - 刷新页面时如何禁止重新发布 - ASP.NET MVC

javascript - Cookie 的有效期不会改变。

php - 如何在 PHP 无限循环中更新页面变量?

c# - 按自定义顺序排序

c# - 不是从 App.Config 获取连接字符串吗?

c# - mySQL 从一个表中选择,从另一个表中加入,然后从新表中选择

c# - 找到未映射的成员(即使忽略该属性)

cookies - 如何收集类似于 panopticlick.eff.org 的信息