Ang*_*ina 4 c# asp.net session webmethod
我得到的错误就像
非静态字段,方法或属性'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();
}
}
Run Code Online (Sandbox Code Playgroud)
不要让你的方法静态.它不需要是静态的,它会阻止您使用任何非静态属性(如Session).做了:
public string Login(string email, string password)
{
....
}
Run Code Online (Sandbox Code Playgroud)
此外,不要连接SQL查询,尤其是来自UI的值.这使您容易受到SQL注入的攻击.使用SQLParameters.
Try this code and please be-ware of SQL Injection - to prevent it, use a Parametrized Query as follows:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30536 次 |
| 最近记录: |