【发布时间】:2017-07-24 17:09:39
【问题描述】:
我创建了一个 ASP.NET Core 网站,并且正在尝试设置身份验证。 FormsAuthentication 不见了,所以我想我必须使用 Identity。我制作了一个使用 HttpContext SignInAsync 事物的系统,但它说 cookie 未初始化。我尝试将 UseIdentity 和 AddIdentity 以及其他 10 项内容添加到 Startup.cs,但它说这些没有定义。我还尝试获取 Identy NuGet 包。
编辑: 启动.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using StarLegacy.Web.Code.Utils;
using System.IO;
using Microsoft.AspNetCore.Authentication.Cookies;
namespace StarLegacy.Web
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
try
{
DBUtils.Init();
}
catch (Exception exception)
{
File.WriteAllText("startuperror.txt", exception.ToString());
Console.Error.WriteLine(exception);
}
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
services.AddAntiforgery();
services.AddAuthorization();
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookieAuthentication();
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" }
);
});
}
}
}
【问题讨论】:
-
之前是否添加了 app.UseCookieAuthentication()?
-
那也不存在:/
-
我建议使用没有 ASP.NET Core Identity 的 cookie 中间件,所以你应该添加 Microsoft.AspNetCore.Authentication.Cookies
-
谢谢,nuget 包使 UseCookieAuthentication 存在。但是,我仍然收到此错误: InvalidOperationException: No authentication handler is configured to handle the scheme: Cookie
-
Microsoft.AspNetCore.Authentication.Cookies 用于创建您自己的中间件,这是我强烈推荐的,它为您提供了更多的灵活性,请看一下:docs.microsoft.com/en-us/aspnet/core/security/authentication/… 另外请在问题中提供您的配置和启动功能代码。附言app.UseCookieAuthentication() 可以错过
标签: c# asp.net asp.net-mvc asp.net-core asp.net-identity