WebService – 3.后台调用WebService,根级别上的数据无效

时间:2024-01-19 16:43:15

1.因为我的webservice返回的是json,

2.ajax传递跨域不安全,

3.contentType: "application/json; charset=utf-8", 这个是直接访问的webservice

 

所以还是采用后台调用

如果引用微软的webService直接new对象,调用方法,就会报错根级别上的数据无效

困扰了我1天,最后的解决方法,

创建辅助类,

    public class WebServiceHelper
{
/// <summary>
///
/// </summary>
/// <param name="url">地址</param>
/// <param name="method">方法</param>
/// <param name="param">json参数</param>
/// <returns></returns>
public static string WebServiceApp(string url, string method, string param)
{
byte[] byteArray = Encoding.UTF8.GetBytes("json=" + param);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + method));
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string phpend = php.ReadToEnd(); return phpend;
}
}

 

 

 

调用方法:

WebService – 3.后台调用WebService,根级别上的数据无效