非静态字段、方法或属性需要对象引用'
本文关键字:对象引用 属性 字段 静态 方法 | 更新日期: 2023-09-27 17:49:35
出现如下错误
非静态字段、方法或对象引用是必需的属性"System.Web.UI.Page.Session.get"
你能建议我在会议中解决这个问题吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.SessionState;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Onclick Submit Button
[WebMethod(EnableSession = true)]
//[System.Web.Services.WebMethod(EnableSession = true)]
public static string Login(string email, string password)
{
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["blogConnString"].ConnectionString);
con.Open();
string res = "0";
SqlDataReader reader;
string sql = "select uid,username from personal where email='" + email + "' and password='" + password + "'";
SqlCommand cmd1 = new SqlCommand(sql, con);
reader = cmd1.ExecuteReader();
while (reader.Read())
{
res = "1";
Session["UID"] = reader["uid"].ToString(); //error line here
Session["UNAME"] = reader["username"].ToString(); //error line here
}
return res;
con.Close();
}
}
尝试这段代码,请注意SQL注入-为了防止它,请使用参数化查询,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.SessionState;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Onclick Submit Button
[WebMethod(EnableSession = true)]
//[System.Web.Services.WebMethod(EnableSession = true)]
public static string Login(string email, string password)
{
var con = ConfigurationManager.ConnectionStrings["blogConnString"].ConnectionString;
con.Open();
string res = "0";
SqlDataReader reader;
string sql = "select uid,username from personal where email=@Email and password=@Password";
using(SqlConnection connection = new SqlConnection(con))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@Email", SqlDbType.String);
command.Parameters["@Email"].Value = email;
command.Parameters.AddWithValue("@Password", password);
reader = command.ExecuteReader();
while (reader.Read())
{
res = "1";
HttpContext.Current.Session["UID"] = reader["uid"].ToString(); //Either Remove Static from Method Declaration or use HttpContext.Current along with session.
HttpContext.Current.Session["UNAME"] = reader["username"].ToString();
}
}
return res;
con.Close();
}
}
不要让你的方法变成静态的。它不需要是静态的,它可以防止您使用任何非静态属性(如Session
)。让它:
public string Login(string email, string password)
{
....
}
另外,不要连接SQL查询,尤其是来自UI的值。这使您容易受到SQL注入的攻击。使用SQLParameters。
你可以用它来插入一个变量到会话:
HttpContext.Current.Session["UID"] = reader["uid"].ToString();
,不要使用静态
public string Login(string email, string password)
{
}