我試圖解析返回數據到C#中的JSON時有一些問題。所以基本上我有一個在SELECT SQL語句中的例子:C#解析返回數據到JSON
[WebMethod]
public string getUserDetails(string userID)
{
DataTable dt = new DataTable();
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnStr"].ConnectionString);
string select = "select * from dbo.User WHERE userID = '" + userID + "'";
sqlConnection.Open();
SqlDataAdapter da = new SqlDataAdapter(select, sqlConnection);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
sqlConnection.Close();
return serializer.Serialize(rows);
}
這些代碼工作正常。但是,當涉及到INSERT SQL語句,我不知道如何返回boolean值傳遞到JSON:
[WebMethod]
public bool addUser(UserModel um)
{
bool result = false;
result = Conversion.intToBool(SplashAwardsDB.executeNonQuery(
"INSERT INTO dbo.User ("
+ "userName, password, firstName, lastName, address, contactNo, birthDate, familyID, familyRole, x, y) "
+ " VALUES ("
+ "'" + um.userName + "', "
+ "'" + um.password + "', "
+ "'" + um.firstName + "', "
+ "'" + um.lastName + "', "
+ "'" + um.address + "', "
+ "'" + um.contactNo + "', "
+ "'" + um.birthDate + "', "
+ "'" + um.familyID + "', "
+ "'" + um.familyRole + "', "
+ "'" + um.x + "', "
+ "'" + um.y + "')"
));
return result;
}
如何序列化的任何指南?
編輯
[WebMethod]
public string checkLoginCredential(string userName, string password)
{
bool result = false;
using (var connection = new SqlConnection(SplashAwardsDB.connectionString))
{
SqlCommand command = new SqlCommand("SELECT userName, password FROM dbo.User WHERE userName = '" + userName + "' AND password = '" + password + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
if (dr.Read())
{
Session["userName"] = dr["userName"];
result = true;
}
}
}
return serializer.Serialize(result);
}
基本上我想檢查登錄憑證。如果用戶名和密碼匹配,我會將用戶名存儲到sesssion中。那麼我該如何修改這個,以便當我的朋友調用這個方法時,它會返回會話數據?
在你走之前,請請Google谷歌「SQL注入」 – RobH 2014-09-22 09:16:37
好吧,但我該怎麼做,因爲我試過這個:System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization .JavaScriptSerializer(); return serializer.Serialize(result);但它會拋出一條錯誤消息,它不能隱式地將字符串轉換爲bool – 2014-09-22 09:17:47
那是因爲'addUser'的返回類型是bool,而您試圖返回一個字符串... – RobH 2014-09-22 09:30:38