Код: Выделить всё
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton();
builder.Services.AddHttpContextAccessor();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.SlidingExpiration = true;
options.AccessDeniedPath = "/Forbidden/";
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization(); ;
app.MapControllers();
using var scope = app.Services.CreateScope();
var httpContextAccessor = scope.ServiceProvider.GetRequiredService();
if (httpContextAccessor is not null)
{
httpContextAccessor.HttpContext ??= new DefaultHttpContext();
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Email, ClaimTypes.Role);
identity.AddClaims(new List
{
new(JwtRegisteredClaimNames.Sub, "JhonDoe"),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new(JwtRegisteredClaimNames.Email, "jhon_doe@gmail.com")
});
var principal = new ClaimsPrincipal(identity);
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
};
await httpContextAccessor!.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authProperties);
}
app.Run();
Необработанное исключение. System.ArgumentNullException: значение не может быть нулевым. (Параметр «поставщик»)
в System.ThrowHelper.Throw(String paramName)
в Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](поставщик IServiceProvider)
в Microsoft.AspNetCore. Authentication.AuthenticationHttpContextExtensions.GetAuthenticationService(контекст HttpContext)
в Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync(контекст HttpContext, схема String, субъект ClaimsPrincipal, свойства AuthenticationProperties)
в Program.$(String[] args) в D:\Desktop\HttpContextTestApp\Program.cs:line 83
at Program.(String[] args)
Есть идеи?
Подробнее здесь: https://stackoverflow.com/questions/784 ... -cannot-be