Из вашего кода список пользователей, кажется, для всех пользователей. Я полагаю, что вы можете получить их, как показано ниже:
var user = _context.User.ToList();
Для того, чтобы установить сеанс и получить его. Вот рабочийдемо, как показано ниже:
1.Controller.cs
public class UsersController : ControllerBase
{
private IUserService _userService;
public const string SessionKeyName = "user";
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpPost("token")]
public IActionResult Authenticate([FromBody]User userParam)
{
var users = new User { Id = 1, FirstName = "Jeevan", LastName = "Nigade", Username = "Jeevan", Password = "jeevan" };
HttpContext.Session.SetComplexData(SessionKeyName, users);
var _users = HttpContext.Session.GetComplexData<User>(SessionKeyName);
try
{
if (string.IsNullOrEmpty(userParam.Username))
{
return StatusCode(400, "Username Cannot Be Null..!!");
}
else if (string.IsNullOrEmpty(userParam.Password))
{
return StatusCode(400, "Password Cannot Be Null..!!");
}
else
{
var user = _userService.Authenticate(userParam.Username, userParam.Password,_users);
if (user == null)
{
return StatusCode(400, "Username or password is incorrect..!!");
}
return Ok(user);
}
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
[Authorize]
[HttpGet("private")]
public IActionResult GetAll()
{
var _users = HttpContext.Session.GetComplexData<User>(SessionKeyName);
var users = _userService.GetAll(_users);
return Ok(users);
}
2.UserService:
public class UserService : IUserService
{
public User Authenticate(string username, string password,User _users)
{
if (_users.Username == username && _users.Password == password)
return _users;
return null;
}
public User GetAll(User _users)
{
return _users;
}
}
3.IUserService:
public interface IUserService
{
User Authenticate(string username, string password,User _users);
User GetAll(User _users);
}
4.SessionExtensions:
public static class SessionExtensions
{
public static T GetComplexData<T>(this ISession session, string key)
{
var data = session.GetString(key);
if (data == null)
{
return default(T);
}
return JsonConvert.DeserializeObject<T>(data);
}
public static void SetComplexData(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
}
5.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IUserService, UserService>();
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseMvc();
}