我正在尝试创建一个将返回超过1个字符串的Web服务。它将返回4个字符串。之前我曾经使用过webservices,而我以前只返回true或false值。但现在我需要更多数据。
这是我的网络服务。
[WebMethod]
public string get_currency(string date, string cur_code) {
string rtn = "";
try
{
using (SqlConnection conn = new SqlConnection("Data Source=xxx-xxxxx;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx"))
{
string selectSql = "select date,code,banknote_buying,banknote_selling from Currencies where date = '" + date + "' and code ='" + cur_code + "'";
SqlCommand comm = new SqlCommand(selectSql, conn);
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
if (dr.Read()) {
rtn = dr["date"].ToString() + dr["code"].ToString() + dr["banknote_buying"].ToString() + dr["banknote_selling"].ToString();
}
}
}
catch (Exception ex)
{
return "Fail";
}
return rtn;
}
如何将它们作为正确的SOAP对象返回
答案 0 :(得分:1)
我最后做了我想做的事。这是我的代码。
[WebMethod]
public Currency_Object get_currency(string date, string cur_code) {
Currency_Object co = new Currency_Object();
try
{
using (SqlConnection conn = new SqlConnection("Data Source=xxx-xxx;Initial Catalog=MB_DB;Persist Security Info=True;User ID=xxx;Password=xxx"))
{
string selectSql = "select date,code,banknote_buying,banknote_selling from Currencies where date = '" + date + "' and code ='" + cur_code + "'";
SqlCommand comm = new SqlCommand(selectSql, conn);
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
if (dr.Read()) {
co.date_ = dr["date"].ToString();
co.code_ = dr["code"].ToString();
co.banknote_buying_ = dr["banknote_buying"].ToString();
co.banknote_selling_ = dr["banknote_selling"].ToString();
}
}
}
catch (Exception ex) { return null; }
return co;
}
}
这就是返回的内容
<Currency_Object xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<date>06.06.2013 00:00:00</date>
<code>USD</code>
<banknote_buying>1,8847</banknote_buying>
<banknote_selling>1,8922</banknote_selling>
</Currency_Object>
答案 1 :(得分:0)
尝试返回字符串[]
[WebMethod]
public **string[]** get_currency(string date, string cur_code) {
**List<string> rtn = new List<string> ();**
try
{
using (SqlConnection conn = new SqlConnection("Data Source=xxx-xxxxx;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx"))
{
string selectSql = "select date,code,banknote_buying,banknote_selling from Currencies where date = '" + date + "' and code ='" + cur_code + "'";
SqlCommand comm = new SqlCommand(selectSql, conn);
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
if (dr.Read()) {
rtn.Add( dr["date"].ToString());
rtn.Add(dr["code"].ToString());
rtn.Add(dr["banknote_buying"].ToString());
rtn.Add(dr["banknote_selling"].ToString());
}
}
}
catch (Exception ex)
{
rtn.Add("Fail");
}
return rtn.ToArray();
}