timofeygusevopal
@timofeygusevopal
asp.net core developer

Как в .net core 3.1 SignalR настроить Hub так что бы обращаться к полю, а не одному емейлу?

Делаю чат, cтолкнулся с проблемой вывода Ника пользователя, после изменения базы данных, не знаю как обратится к каким либо полям пользователя которые я указываю при регистрации

Moй хаб:
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace Project
{
    
   
    public class ChatHub : Hub
    {
        
        public async Task SendMessage(string message)
        {
            await Clients.All.SendAsync("newMessage", Context.ConnectionId, message);
        }
    }
}


Класс Модели:

namespace Project.Models
{
    public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }


        public int? RoleId { get; set; }
        public Role Role { get; set; }


    }
    
}


Контроллер Аккаунта
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Project.Models;

namespace RolesApp.Controllers
{
    public class AccountController : Controller
    {
        private ApplicationContext _context;
        public AccountController(ApplicationContext context)
        {
            _context = context;
        }
        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await _context.Users.FirstOrDefaultAsync(u => u.Email == model.Email);
                if (user == null)
                {
                    
                    user = new User { Email = model.Email, UserName = model.UserName,  Password = model.Password };
                    Role userRole = await _context.Roles.FirstOrDefaultAsync(r => r.Name == "user");
                    if (userRole != null)
                        user.Role = userRole;

                    _context.Users.Add(user);
                    await _context.SaveChangesAsync();

                    await Authenticate(user); // аутентификация

                    return RedirectToAction("Index", "Home");
                }
                else
                    ModelState.AddModelError("", "Некорректные логин и(или) пароль");
            }
            return View(model);
        }
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await _context.Users
                    .Include(u => u.Role)
                    .FirstOrDefaultAsync(u => u.Email == model.Email && u.Password == model.Password);
                if (user != null)
                {
                    await Authenticate(user); // аутентификация

                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", "Некорректные логин и(или) пароль");
            }
            return View(model);
        }
        private async Task Authenticate(User user)
        {
            // создаем один claim
            var claims = new List<Claim>
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
                new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role?.Name)
            };
            // создаем объект ClaimsIdentity
            ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType,
                ClaimsIdentity.DefaultRoleClaimType);
            // установка аутентификационных куки
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
        }
    }
}

Класс подключения к бд
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Project.Models
{
    public class ApplicationContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public ApplicationContext(DbContextOptions<ApplicationContext> options)
            : base(options)
        {
          //  Database.EnsureDeleted();   // удаляем бд со старой схемой
          //  Database.EnsureCreated();
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            string adminRoleName = "admin";
            string userRoleName = "user";

            string adminEmail = "timofey@gmail.com";
            string adminPassword = "lol";

            // добавляем роли
            Role adminRole = new Role { Id = 1, Name = adminRoleName };
            Role userRole = new Role { Id = 2, Name = userRoleName ,};

            User adminUser = new User { Id = 1, Email = adminEmail,  Password = adminPassword, RoleId = adminRole.Id };

            modelBuilder.Entity<Role>().HasData(new Role[] { adminRole, userRole });
            modelBuilder.Entity<User>().HasData(new User[] { adminUser });
            base.OnModelCreating(modelBuilder);
        }
    }
}


Проблема в том как обратится к полю UserName текущего пользователя через хаб
  • Вопрос задан
  • 141 просмотр
Пригласить эксперта
Ответы на вопрос 1
krakoss
@krakoss
React + C# + PostgreSQL
предложу следующую реализацию
вместо UserId - можно получить любые данные из таблицы dbo.users
// это в Hub
// Получение UserId используя string email = HttpContext.Current.Request.Cookies["ep"]["e"]
        public string NameUserId()
        {
            if (HttpContext.Current != null && HttpContext.Current.Request.Cookies["ep"] != null)
            {
                string email = HttpContext.Current.Request.Cookies["ep"]["e"];
                idUser = UsersDAL.GetUserByEmail(email).Id.ToString();
            }
            return idUser;
        }
// это public class UsersDAL : BaseDataAccess 
public static User GetUserByEmail(string email)
        {
            User result = null;
            const string query = @"select * from dbo.users where email=@Email and deleted=false";
            using (var connection = new NpgsqlConnection(connStr))
            {
                connection.Open();
                if (connection.State == System.Data.ConnectionState.Open)
                {
                    using (var command = new NpgsqlCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("Email", email);

                        try
                        {
                            var reader = command.ExecuteReader();
                            if (reader.Read())
                                result = ReadUserInfo(reader);
                            reader.Close();
                        }
                        catch (Exception ex)
                        {
                            string methodName = MethodBase.GetCurrentMethod().Name;
                            throw new Exception("in UsersDAL." + methodName + "(): " + ex);
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
                }
                else
                {
                    // conn Open to SQLite DB
                }
            }

            return result;
        }
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы