0
我想使用Http-Post方法向Web服務發出請求。這是我在C#中的代碼。HttpWebRequest.GetResponse給內部服務器錯誤
static void Main(string[] args)
{
var _url = "http://localhost/EventWebService/EventWebService.asmx";
var _action = "http://localhost/EventWebService/EventWebService.asmx?op=GetPerson";
XmlDocument soapEnvelope = new XmlDocument();
soapEnvelope.LoadXml(@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body><GetPerson xmlns=""http://tempuri.org/"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><name>Brad</name><surname>Pitt</surname><age>51</age></GetPerson></SOAP-ENV:Body></SOAP-ENV:Envelope>");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
request.Headers.Add("SOAPAction", _action);
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Accept = "text/xml";
request.Method = "POST";
InsertSoapEnvelopeIntoWebRequest(soapEnvelope, request);
WebResponse response = request.GetResponse();
StreamReader rd = new StreamReader(response.GetResponseStream());
Console.WriteLine(rd.ReadToEnd());
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
這裏是我的Web服務方法和使用的一類:
[WebMethod]
[ return: XmlElement("ReturnValueElement",IsNullable=false)]
public Person GetPerson([XmlElement("Name")] string name, [XmlElement("Surname")] string surname, [XmlElement("Age")] int age)
{
return new Person(name, surname, age);
}
public class Person
{
string Name { get; set; }
string Surname { get; set; }
int Age { get; set; }
public Person() { }
public Person(string _name, string _surname, int _age)
{
Name = _name;
Surname = _surname;
Age = _age;
}
};
這裏是我的配置文件配置Web服務:
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="Documentation"/>
<add name="HttpPostLocalhost"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
在主,當我調試WebResponse response = request.GetResponse();
行,我得到與協議錯誤狀態的內部服務器錯誤(500)。
任何想法?謝謝你們。
你爲什麼不使用常規的Web引用或WCF一起? – fejesjoco 2014-11-22 14:37:56