由于项目需要:自己写了一个WebserviceDemo,把遇到的问题记下来。
方式一 :使用代理类来访问Webservice,此方式不讲解,感觉复杂(神坑)。
(生成的代理路径 C:\Users\admin\AppData\Local\Temp\FrameWork.WebService.DynamicWebServiceCalling.doAction5DD81ED96F54BCFBC7A4634BB01BE5CA.dll)
方式二:HTTP方式调用两个测试工具
1.POSTMan
2.Fiddler
3.本地测试什么都没有问题,部署到阿里云远程服务器,在本地用上面的调用工具,就提示500错误。
原来web.config里面默认Post设置是不允许远程调用webservice,改变一下配置就可以了。
如果想在远程可以正常调用,需要修改web.config,在system.web节下面加上下面一段话即可。
<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation targetFramework="4.0" />
<webServices >
<protocols >
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
</webServices>
</system.web>
</configuration>
下面是使用HTTP调用webservice的代码
var url = "http://localhost:9000/WebServiceGSMTest.asmx/GetToken3";
string data = "Id=11111&name=222";
var retBack = HttpHelpers.RequestData(url, data, ReqMethod.POST, null, "application/x-www-form-urlencoded");
public class HttpResponse
{
public bool Status;
public string RetStr;
public Exception Exception;
}
public enum ReqMethod
{
POST,
GET,
}
/// <summary>
///
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="method"></param>
/// <param name="header"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static HttpResponse RequestData(string url, string data, ReqMethod method, WebHeaderCollection header, string contentType = "application/json")
{
HttpWebRequest request = null;
HttpWebResponse response = null;
Stream stream1 = null;
StreamReader sr = null;
HttpResponse res = new HttpResponse();
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method.ToString();
if (header != null)
{
request.Headers = header;
}
request.ContentType = contentType;
if (method == ReqMethod.POST)
{
byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
request.ContentLength = postdatabyte.Length;
request.KeepAlive = true;
Stream stream;
stream = request.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length); //设置请求主体的内容
stream.Close();
}
//接收响应
response = (HttpWebResponse)request.GetResponse();
stream1 = response.GetResponseStream();
sr = new StreamReader(stream1);
string str = sr.ReadToEnd();
res.Status = true;
res.RetStr = str;
}
catch (Exception ex)
{
res.Exception = ex;
}
finally
{
if (stream1 != null)
{
stream1.Close();
stream1.Dispose();
}
if (sr != null)
{
sr.Close();
sr.Dispose();
}
}
return res;
}