C# 如何检查数据库的特定列中是否存在用户名
我正在将C与ASP.Net表一起使用。我试图检查用户何时访问我的web应用,他们的用户ID是否列在web应用中显示的表中名为UserID的列中。如果不是,那么我想将它们重定向到错误页面 我需要这个来检查页面何时加载,显然它需要在页面加载。我只是不知道如何调用表中的列并让它检查用户ID 这就是我到目前为止所做的:C# 如何检查数据库的特定列中是否存在用户名,c#,asp.net,C#,Asp.net,我正在将C与ASP.Net表一起使用。我试图检查用户何时访问我的web应用,他们的用户ID是否列在web应用中显示的表中名为UserID的列中。如果不是,那么我想将它们重定向到错误页面 我需要这个来检查页面何时加载,显然它需要在页面加载。我只是不知道如何调用表中的列并让它检查用户ID 这就是我到目前为止所做的: protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string UserID = HttpContext.Current.Request.LogonUserIdentity.Name.Substring(4);
SQLUserID();
if (UserID != //'Whatever values are in the UserID column'//)
{
Server.Transfer("ErrorPage.aspx");
}
SQLCmd = SqlDataSource1.SelectCommand;
GridView1.DataBind();
}
}
字符串UserID为我提供了用户的用户ID。SQLUserID=从信息中选择UserId。我知道我打电话的方式不对,但我不知道怎么做 它可以帮助您:
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand check_User_Name ("SELECT COUNT(*) FROM tblUser WHERE (UserID=@UserID)",conn);
check_User_Name.Parameters.AddWithValue("@UserID,UserID);
int userExist=(int)check_User_Name.ExecuteScalar();
if(userExist>0)
{
//Login
}
else
{
Server.Transfer("ErrorPage.aspx");
}
只需编写连接字符串并享受它。下面是我如何让它在页面加载下工作的
您肯定应该加载实体框架。你用的是.NETCore还是.NET4X?老实说,我不知道那是什么意思,但我想我用的是.netCore@derekg8881,您没有使用.Net core。可以从该项目的“属性”选项卡进行检查。这很可能是.Net framework的某个版本。什么是check_User_Name?我编辑了它。谢谢。它是一个SqlCommand类型的对象。当我将它放入if时,它只是充满了错误!Page.IsPostBack
{
string connectionString = "Data Source=###;Initial Catalog=###;Integrated Security=True";
if (!Page.IsPostBack)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(UserID) from Info WHERE UserID like @UserID", sqlConnection))
{
string UserID = HttpContext.Current.Request.LogonUserIdentity.Name.Substring(4);
sqlCommand.Parameters.AddWithValue("@UserID", UserID);
int userCount = (int)sqlCommand.ExecuteScalar();
if (userCount == 0)
{
Server.Transfer("ErrorPage.aspx");
}
SQLCmd = SqlDataSource1.SelectCommand;
GridView1.DataBind();
}
}
}