Web 服务器端;
[Serializable]
public class product
{
public string code { get; set; }
public string name { get; set; }
public string description { get; set; }
}
[WebMethod]
public static string testmethod(product pr)
{
if (pr == null)
return "parameter is null";
return "Succesfull! Parameters you sent : " + pr.code +", "+ pr.name +","+ pr.description;
}
客户端
void WebService_Test()
{
using (WebClient client = new WebClient())
{
try
{
product pr = new product();
pr.code = "LY700";
pr.name = "Lenovo Y700";
pr.description = "notebook";
string pars = Newtonsoft.Json.JsonConvert.SerializeObject(pr, Formatting.Indented);
string postUrl = "http://192.168.0.110/integration.aspx/testmethod";
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
string result = client.UploadString(postUrl, "POST", pars);
Console.Write(result);
}
catch (Exception ex) { Console.Write(ex.Message); }
}
}
我可以成功发送或返回字符串参数,但我必须使用对象作为参数,就像我上面创建的此示例一样。但它说,远程服务器返回500(内部服务器错误( 这段代码有什么问题?
花了几个小时后,我终于找到了!
问题出在这里:
string result = client.UploadString(postUrl, "POST", pars);
它必须是这样的,
product pr = new product();
// pr definitons..
string par = Newtonsoft.Json.JsonConvert.SerializeObject(pr, Formatting.Indented);
string result = client.UploadString(postUrl, "POST", "{pr:"+ par + "}");
还要确保使用的参数名称与在 webmethod输入参数中定义的参数名称相同。 否则,您将收到错误。