Сначала я сохранил пользователя в синглтоне UserService< /code> как статическое свойство, но потом я понял, что это приводит к использованию одного и того же свойства User во всех экземплярах приложения, поэтому я попытался добавить сеансы и аутентификацию, но я просто не понимаю, как все это работает, и я не понимаю. даже знаю, с чего начать его изучение.
Это мой UserService прямо сейчас:
Код: Выделить всё
using Market.Data.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Diagnostics;
namespace Market.Services
{
public class UserService : IUserService
{
private readonly IHttpClientFactory factory;
private readonly IHttpContextAccessor httpContextAccessor;
private readonly HttpClient client;
private User? User;
public UserService(IHttpClientFactory httpClientFactory, IHttpContextAccessor httpContextAccessor)
{
factory = httpClientFactory;
client = factory.CreateClient();
client.BaseAddress = new Uri("https://farmers-market.sommee.com/api/");
this.httpContextAccessor = httpContextAccessor;
User = GetUser();
}
private async Task SaveUserToContext(User user)
{
var claims = new List
{
new Claim(ClaimTypes.UserData, JsonSerializer.Serialize(user)),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
httpContextAccessor.HttpContext.User = new ClaimsPrincipal(claimsIdentity);
}
public async Task Login(string email, string password)
{
var url = $"https://farmers-market.somee.com/api/users/login?email={email}&password={password}";
var response = await client.GetAsync(url);
var result = new User();
if (response.IsSuccessStatusCode)
{
var stringResponse = await response.Content.ReadAsStringAsync();
Console.WriteLine(stringResponse);
result = JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
User = result;
await SaveUserToContext(result!);
}
else
{
throw new HttpRequestException(response.ReasonPhrase);
}
if (result == null)
{
throw new Exception("Error with login");
}
return result;
}
public async Task Register(User user)
{
var url = $"https://farmers-market.somee.com/api/users/add";
var jsonParsed = JsonSerializer.Serialize(user, new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
HttpContent content = new StringContent(jsonParsed.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
return response.StatusCode;
}
public Task RemoveOrderAsync(int orderId)
{
if (User == null)
{
throw new Exception("User is not authenticated");
}
User.SoldOrders.Remove(User.SoldOrders.Single(x => x.Id == orderId));
return Task.CompletedTask;
}
public void AddApprovedOrder(int id)
{
User!.SoldOrders.Single(x => x.Id == id).IsApproved = true;
}
public void AddDeliveredOrder(int id)
{
User!.SoldOrders.Single(x => x.Id == id).IsDelivered = true;
}
public User? GetUser()
{
var saved = httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.UserData);
if (saved == null)
return null;
User = JsonSerializer.Deserialize(saved);
return User;
}
}
}
Код: Выделить всё
using Market.Services;
using Market.Services.Firebase;
using Market.Services.Inventory;
using Market.Services.Offers;
using Market.Services.Orders;
using Market.Services.Reviews;
using Microsoft.AspNetCore.Authentication.Cookies;
using Market.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Market.Data.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30); // Adjust timeout as needed
options.Cookie.HttpOnly = true;
options.Cookie.Name = "SessionCookie_" + Guid.NewGuid().ToString();
options.Cookie.IsEssential = true;
});
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
// Set a unique cookie name for this instance of the app
options.Cookie.Name = "AuthCookie_" + Guid.NewGuid().ToString(); // Or use another unique value
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Подробнее здесь: https://stackoverflow.com/questions/790 ... t-core-mvc
Мобильная версия