尝试这种方式:
LoginController.cs
using System.Data.Odbc;
using System.Web.Configuration;
public ActionResult LoginReadData()
{
string query = "Select * from login where name=@name and password=@password";
//using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString))
OR
using (OdbcConnection connection = new OdbcConnection("Your Connection String")) //here you need to add connection
{
OdbcCommand command = new OdbcCommand(query, connection);
connection.Open();
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string name = reader[0].ToString();
string password = reader[1].ToString();
if (name != null && password != null)
{
return RedirectToAction("Index", "Home");
}
else
{
return View("Create", "Registration");
}
}
reader.Close();
}
return View();
}
它is可能有效。
但是,您最有可能激活了Cookie身份验证或类似身份验证,这意味着MVC将把用户重定向回登录页面,因为找不到身份验证Cookie。
返回重定向之前,您必须创建cookie。
如何执行取决于所运行的MVC版本。
在return RedirectToAction("Index", "Home");
之前添加以下内容
// Which claims depends on what kind of information you want to store about the user
var claims = new[] { new Claim("ClaimTypes.Name", name) };
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
Context.Authentication.SignIn(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
并且这里提供了ASP.NET Core MVC示例:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1