【发布时间】:2021-03-24 16:25:18
【问题描述】:
我是 ASP.NET Core 的新手,我创建了一个登录页面,通过会话进行了简单的身份验证。我正在尝试制作一个可以将您注销的按钮,但我不知道该怎么做。这是我想出的:
这是我的控制器:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
IConfiguration _Configuration;
SecurityService _securityService;
public HomeController(ILogger<HomeController> logger,
IConfiguration configuration,
SecurityService securityService)
{
_logger = logger;
_Configuration = configuration;
_securityService = securityService;
}
public IActionResult Index()
{
var loggedIn = HttpContext.Session.GetString("SessionUser");
if(loggedIn == "admin")
{
return View();
}
else
{
return View("Login");
}
}
public IActionResult Login(UserModel user)
{
Boolean success = _securityService.Authenticate(user, _Configuration);
if (success)
{
HttpContext.Session.SetString("SessionUser", user.Username);
return RedirectToAction("Index");
}
else
{
return View("Login");
}
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
这是我的 SecurityDAO,我在其中查找用户是否存在于数据库中:
public class SecurityDAO
{
internal bool FindByUser(UserModel user, IConfiguration Configuration)
{
string connectionString = Configuration["ConnectionStrings:Database"];
bool success = false;
string queryString = "SELECT * FROM users WHERE username = @username AND password = @password";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand command = new MySqlCommand(queryString, connection);
command.Parameters.Add("@username", MySqlDbType.VarChar, 50).Value = user.Username;
command.Parameters.Add("@password", MySqlDbType.VarChar, 50).Value = user.Password;
try
{
connection.Open();
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
success = true;
}
else
{
success = false;
}
}
catch (Exception ex)
{
throw ex;
}
}
return success;
}
}
这是我的安全服务:
public class SecurityService
{
SecurityDAO daoService = new SecurityDAO();
public bool Authenticate(UserModel user, IConfiguration Configuration)
{
return daoService.FindByUser(user, Configuration);
}
}
先谢谢了! 最好的问候马克斯
【问题讨论】:
-
您是否考虑过使用
SignInManager<TUser>进行身份验证?然后,您只需在控制器内的适当操作方法中使用 SignInManager.SignOutAsync() 方法 -
我的意思是,您是否考虑过使用 MS Identity 作为您的授权服务,而不是自己创建? MS Identity 有许多开箱即用的解决方案来满足您的需求,例如 docs.microsoft.com/en-us/dotnet/api/…
-
我在控制器中创建了一个简单的Logout方法或者IActionResult,但是如何用按钮调用呢?
-
一个按钮可以通过
asp-action标签调用。<a class="btn" asp-action="Logout" asp-controller="Home">Logout</a>。如果用户已登录,您将需要一种仅填充此按钮的方法,而这正是 Identity 可以提供帮助的地方。例如,@if (User?.Identity.IsAuthenticated ?? false)确定是否显示注销按钮。您可能需要传递一个包含“SessionUser”字符串的模型,如果它为空,则可能隐藏 Logout 按钮 -
我不确定你能做到。我在下面添加了相同效果的答案。很高兴你让它工作了
标签: c# asp.net .net asp.net-core-mvc