-1
net和im正在製作一個web服務,用戶在其中註冊並登錄。我做了一個數據庫。其中「ID」,「用戶名」,「密碼」。在webserive中顯示哪個用戶登錄 。此代碼不起作用(name = reader [0] .ToString(); return name;)name是紅線。 PLZ解釋或做校正什麼是錯在何處IM誤將web服務連接到sql服務器
這裏是我的連接字符串
<connectionStrings>
<add connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Abdul Samad\Documents\Visual Studio 2013\Projects\WebApplication8\WebApplication8\App_Data\webserver_database.mdf;Integrated Security=True" name="webconnectionstr"/>
</connectionStrings>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication8
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public int Register(string name , string password)
{
SqlConnection connection = new SqlConnection();
try
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["webconnectionstr"].ToString();
connection.Open();
SqlCommand cmd = new SqlCommand(@"insert into [userTable] (username,password) values
('" + name + "','" + password + "')", connection);
cmd.ExecuteNonQuery();
return 1;
}
catch(Exception ex) {
return 0;
}
finally
{
connection.Close();
}
}
[WebMethod]
public int getUsername(int id)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["webconnectionstr"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand(@"select username from [userTable] where userId='" + id + "'", con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
name = reader[0].ToString();
}
return cmd;
con.Close();
}
}
}
爲什麼你返回cmd而不是名字? 「getUsername」方法必須返回字符串,而不是int。你能告訴我們哪個錯誤給你的代碼?你確定sql查詢返回數據嗎? – Nacho 2014-09-24 12:49:07
此代碼將非常容易受到SQL注入攻擊。它實際上是乞求被黑客攻擊。另外:不要在您的數據庫中存儲密碼;存儲密碼_hashes_。 – 2014-09-24 13:45:36
即時新作在這只是爲了學習 – 2014-09-25 06:35:47