WebClient UploadString

时间:2013-12-13 22:21:34

标签: .net json post webclient

有问题。

使用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
  }
]

为什么我会收到错误?

1 个答案:

答案 0 :(得分:0)

虽然我质疑您尝试使用代码完成的任务,但最终您获得HTTP 500响应的原因是因为您将数据发布到不具备该功能的Web服务方法接受任何参数。

要使用POST呼叫getProducts,您需要使用空字符串调用wc.UploadString(...)

string result = wc.UploadString("http://localhost:3523/WS/iqws.asmx/getProducts", String.Empty);

这将检索产品列表。要上传产品,您需要一种不同的Web服务方法,例如:

public class Product
{
    public String Name { get; set; }
    public String Code { get; set; }
    public String Money { get; set; }
    public String Images { get; set; }
    public String Comments { get; set; }
}

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class iqws : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string getProducts()
    {
        List<Product> prd = new List<Product>();
        //{
        //  new Product() { Name = "myname", Code = "mycode" },
        //  new Product() { Name = "myname2", Code = "mycode2" }
        //};
        using (SqlConnection cn = new SqlConnection(ado.cnStr))
        {
            SqlCommand cmd = new SqlCommand("SELECT * FROM Product", cn);
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Product p = new Product();
                p.Name = dr["name"].ToString();
                p.Money = dr["money"].ToString();
                prd.Add(p);
            }
        }

        return new JavaScriptSerializer().Serialize(prd);
    }

    [WebMethod]
    [ScriptMethod]
    [GenerateScriptType(typeof(Product))]
    public void addProduct(Product p)
    {
        // Place your validation code here to ensure the Product property values are in expected whitelists.
        using (SqlConnection cn = new SqlConnection(ado.cnStr))
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO Product (Name, Money) VALUES (@Name, @Money)", cn);
            cmd.Parameters.AddWithValue("@Name", p.Name);
            cmd.Parameters.AddWithValue("@Money", p.Money);

            cn.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

并查询您的服务:

        var ser = new JavaScriptSerializer();
        WebClient wc = new WebClient();
        wc.Headers[HttpRequestHeader.ContentType] = "application/json";
        string url = Request.Url.GetLeftPart(UriPartial.Authority) + "/WS/iqws.asmx/getProducts";
        string json = wc.UploadString(url, String.Empty);
        var data = ser.Deserialize<Dictionary<String, String>>(json);
        List<Product> products = ser.Deserialize<List<Product>>(data["d"]);
相关问题