要在.NET中检索已登录/已连接的用户列表,您可以使用ASP.NET Core的Identity模块。以下是一个简单的示例,说明如何实现此目标:
Microsoft.AspNetCore.Identity
Microsoft.AspNetCore.Identity.EntityFrameworkCore
ConfigureServices
方法中添加以下代码:services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
using Microsoft.AspNetCore.Identity;
namespace YourApp.Models
{
public class ApplicationUser : IdentityUser
{
}
}
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using YourApp.Models;
namespace YourApp.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using YourApp.Models;
namespace YourApp.Controllers
{
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public AccountController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<IActionResult> LoggedInUsers()
{
var users = await _userManager.GetUsersInRoleAsync("LoggedIn");
return View(users);
}
}
}
@model IEnumerable<YourApp.Models.ApplicationUser>
<h2>Logged In Users</h2><table class="table">
<thead>
<tr>
<th>Username</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<td>@user.UserName</td>
<td>@user.Email</td>
</tr>
}
</tbody>
</table>
endpoints.MapControllerRoute(
name: "logged-in-users",
pattern: "logged-in-users",
defaults: new { controller = "Account", action = "LoggedInUsers" });
现在,您可以运行应用程序并访问"/logged-in-users"路径,以查看已登录/已连接的用户列表。
请注意,这个示例仅用于演示目的,您可能需要根据您的实际需求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云