0
雖然後處理用的Web服務,我得到錯誤
iqws webservis = new iqws();
WebClient wc = new WebClient();
var ser = new JavaScriptSerializer();
var serializedResult = ser.Serialize(webservis.getProducts());
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
string result = wc.UploadString("http://localhost:3523/WS/iqws.asmx/getProducts", serializedResult);
var table = ser.Deserialize<Dictionary<string, dynamic>>(result);
但有錯誤:遠程服務器返回錯誤:(500)內部服務器錯誤。
爲什麼?
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class iqws : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getProducts()
{
List<products> prd= new List<products>();
SqlConnection cn = new SqlConnection(ado.cnStr);
SqlCommand cmd = new SqlCommand("SELECT * FROM products", cn);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
products p = new products();
p.name = dr["name"].ToString();
p.money = dr["money"].ToString();
prd.Add(p);
}
var jsonSerialiser = new JavaScriptSerializer();
return jsonSerialiser.Serialize(prd);
}
}
和JSON後沒有問題..
$.ajax({
type: "POST",
url: "/WS/iqws.asmx/getProducts",
contentType: "application/json; charset=utf-8",
//data: {},
dataType: "json",
success: function (data) {
$("#jsonvalue").html(data.d);
},
error: function (xhr, status, error) {
$("#jsonvalue").html(xhr.responseText);
}
});
和結果;
[
{
"name": "iPhone 4s Gold",
"code": null,
"money": "1899,0000",
"images": null,
"comments": null
},
{
"name": "iPhone 5s Black",
"code": null,
"money": "2000,0000",
"images": null,
"comments": null
}
]
爲什麼我會收到錯誤?
爲什麼你試圖將產品上傳到'的getProducts()'?您首先通過調用'webservis.getProducts()'直接從代碼中獲取產品,然後嘗試通過調用'wc.UploadString(...)'來將該產品集合上傳到'getProducts()'方法URL。如果你想使用POST上傳產品,那麼你需要另一個'addProducts(products [] p)'方法來接受'產品'數組作爲參數。如果您想下載產品列表,請使用類似'wc.DownloadString(...)'的東西來使用GET。 – nekno