I am trying to do a SOAP request but the server is returning an 500 error.
The SOAP request returns correctly the XML message via jmeter for example, so it must be something in my code, but i fail to see what. Can you help?
private void soapRequest(string regID)
{
string soapReq= #"<?xml version=""1.0"" encoding=""utf-8""?>";
soapReq= "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:mpc=\"urn://mobility-platform.de/mpcustomerdb/\">\n";
soapReq += "<soapenv:Header/>\n";
soapReq += "<soapenv:Body>\n";
soapReq += "<mpc:findRegistrationByID>\n";
soapReq += "<registrationID>" + regID + "</registrationID>\n";
soapReq += "</mpc:findRegistrationByID>\n";
soapReq += "</soapenv:Body>\n";
soapReq += "</soapenv:Envelope>";
//Builds the connection to the WebService.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://url?wsdl");
req.Credentials = new NetworkCredential("user", "pass");
req.Headers.Add("SOAP:Action");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
//Passes the SoapRequest String to the WebService
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soapReq.ToString());
}
}
try
{
//Gets the response
HttpWebResponse soapResponse = (HttpWebResponse)req.GetResponse();
//Writes the Response
Stream responseStream = soapResponse.GetResponseStream();
//read the stream
XmlDocument soapResponseXML = new XmlDocument();
StreamReader responseStreamRead = new StreamReader(responseStream);
soapResponse.ContentType = "text/xml";
//MessageBox.Show(responseStreamRead.ReadToEnd().ToString());
string soapURL = responseStreamRead.ReadToEnd().ToString();
soapResponseXML.LoadXml(soapURL);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
Here is the soap request
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mpc="urn://mobility-platform.de/mpcustomerdb/">
<soapenv:Header/>
<soapenv:Body>
<mpc:findRegistrationByID>
<registrationID>2304580</registrationID>
</mpc:findRegistrationByID>
</soapenv:Body>
</soapenv:Envelope>
Later edit:
If i change
req.Headers.Add("SOAP:Action"); to:
req.Headers.Add("SOAPAction", ""\"http://url\"" + "findRegistrationByID");
i get an different error:
"This property is not implemented by this class"
Is not very easy to make an proper soap request with this method. I am strongly recommending to use rather the whole web service, and rather make the request like this:
WebService aa = new WebService;
registrationName = aa.findRegistrationByID("123");
This will accomplish all the above code ;)
Related
I am using XDocument to manually build a SOAP request and send it using HTTPWebRequest. The final output of the XDocument object is valid and when I capture and send it to the end point using SOAPUI it works fine, however; I have been unable to get this to work using HTTPWebRequest. I receive internal server server errors, but nothing really specific that I can work from. I am excluding the XDocument object for brevity. Any guidance would be appreciated.
var _url = "http://xxx.xx.x.xx:9191/aa/bb/cc/dd";
var _action = "http://xxx.xx.x.xx:9191/aa/bb/cc/dd?op=submit";
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(_url);
webRequest.Headers.Add(#"SOAPAction", _action);
webRequest.Credentials = new NetworkCredential("xxxxx", "xxxxxx");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
using (Stream stream = webRequest.GetRequestStream())
{
xd.Save(stream);
}
// get the response from the completed web request.
string soapResult;
try
{
using (WebResponse webResponse = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Response.Write(soapResult);
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
Response.Write("Status Code : " + ((HttpWebResponse) ex.Response).StatusCode);
Response.Write("Status Description : " + ((HttpWebResponse) ex.Response).StatusDescription);
}
}
UPDATE (included small sample of SOAP):
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<enrollment xmlns="xxxxxxxxxxx">
<asOfDate xmlns="">2018-01-01</asOfDate>
<activate xmlns="">false</activate>
<subscription xmlns="">
<receiptDate>2018-06-01</receiptDate>
<accountMatchData>
<accountHccIdentifier>
<accountHccIdentificationNumber>xxxxxxxxxx</accountHccIdentificationNumber>
</accountHccIdentifier>
<asOfDate>2018-01-01</asOfDate>
</accountMatchData>
<informationSourceCode>
<codeEntry>3</codeEntry>
</informationSourceCode>
</subscription>
</enrollment>
</s:Body>
</s:Envelope>
UPDATE (Solved):
I cannot believe it was something as stupid as how it was sending the credentials. I used the below code to generate the credentials and add them to the HTTPWebRequest and it worked.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("xxxx" + ":" + "xxxxxxx"));
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(_url);
webRequest.Headers[HttpRequestHeader.Authorization] = string.Format(
"Basic {0}", credentials);
I am trying to consume web service using SOAP request in asp.net C# but it is failing with
The remote server returned an error: (500) Internal Server Error.
Below is my web service request code:
public static HttpWebRequest CreateWebRequest()
{
string action = "http://localhost:8081/Service.asmx?op=getData";
string url = "http://localhost:8081/Service.asmx";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "application/soap+xml; charset=utf-8";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.Timeout = 30000;
return webRequest;
}
public static XmlDocument ServiceCall()
{
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = CreateSoapEnvelope("MyUser", "MyUser", "MyUser");
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne(20 * 1000);
string soapResult;
using (WebResponse webResponse = request.EndGetResponse(asyncResult))
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
XmlDocument resp = new XmlDocument();
resp.LoadXml(soapResult);
return resp;
}
private static XmlDocument CreateSoapEnvelope(string userName, string password, string DCSCommand)
{
StringBuilder builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
builder.Append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
builder.Append("<soap12:Body>");
builder.Append("<geteFliteData xmlns=\"http://test.org\">");
builder.Append("<userName>" + userName + "</userName>");
builder.Append("<password>" + password + "</password>");
builder.Append("<DCSCommand>" + DCSCommand + "</DCSCommand>");
builder.Append("</geteFliteData>");
builder.Append("</soap12:Body>");
builder.Append("</soap12:Envelope>");
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(builder.ToString());
return soapEnvelop;
}
Note: When I am consuming this web service using WSDL file it is working fine and returns expected XML
This is how our outgoing soap looks like in code behind..
It is giving me an error HTTP 500.. I have no control over the service. Just the client to consume this webservice
https://mn-its.dhs.state.mn.us/MnHieEligAdapterWebServiceImpl/spring-ws/EligibilityAdapterMITA
Error
ns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header/>
<soapenv:Body><soapenv:Fault>
<faultcode>soapenv:Server</faultcode><faultstring>WSWS4117E: An attempt was made to add an SOAPEnvelope with a protocol of SOAP 1.2 Protocol to a
SOAPMessage with a protocol of SOAP 1.1 Protocol.</faultstring>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
I understand this is not the best way to do soap in wcf.. I mean like appending it in a stringbuilder but the request involves sending cookies, credentails in a Http header. This is the reason we have done so.
C# code
StringBuilder SoapEnvelope = new StringBuilder();
SoapEnvelope.Append("<soap:Envelope ");
SoapEnvelope.Append("xmlns:soap=");
SoapEnvelope.Append("\"http://www.w3.org/2003/05/soap-envelope\"");
SoapEnvelope.Append(" xmlns:cor=");
SoapEnvelope.Append("\"http://www.caqh.org/SOAP/WSDL/CORERule2.2.0.xsd\">");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("<soap:Header/>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("<soap:Body>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("<cor:COREEnvelopeRealTimeRequest>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("<PayloadType>X12_270_005010X279A1</PayloadType>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("<ProcessingMode>RealTime</ProcessingMode>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("<PayloadID>" + DateTime.Now.Ticks.ToString().Substring(10) + "</PayloadID>");
SoapEnvelope.Append(Environment.NewLine);
string Tdate = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
SoapEnvelope.Append("<TimeStamp>" + Tdate + "</TimeStamp>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("<SenderID>" + PayerDetails.SenderID + "</SenderID>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("<ReceiverID>" + PayerDetails.ReceiverID + "</ReceiverID>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("<CORERuleVersion>2.2.0</CORERuleVersion>");
SoapEnvelope.Append(Environment.NewLine);
Query270 = Generate270(production, UseAlternateProvider);
SoapEnvelope.Append("<Payload>");
SoapEnvelope.Append(Query270);
SoapEnvelope.Append("</Payload>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("</cor:COREEnvelopeRealTimeRequest>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("</soap:Body>");
SoapEnvelope.Append(Environment.NewLine);
SoapEnvelope.Append("</soap:Envelope>");
cookie.Add(new Uri("https://mn-its.dhs.state.mn.us"), new System.Net.Cookie("OBBasicAuth", "fromDialog"));
cookie.Add(new Uri("https://mn-its.dhs.state.mn.us"), new System.Net.Cookie("ObSSOCookie", "loggedoutcontinue"));
byte[] SoapEnvelopeBytes = null;
SoapEnvelopeBytes = Encoding.UTF8.GetBytes(SoapEnvelope.ToString());
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(PayerDetails.TestURL);
System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest)webRequest;
httpRequest.CookieContainer = cookie;
httpRequest.Method = "POST";
httpRequest.UserAgent = "Mozilla/5.0";
httpRequest.ContentType = "text/xml;charset=UTF-8";
httpRequest.Headers.Add("SOAPAction", "EligXsdRealTimeTransaction");
httpRequest.Credentials = new System.Net.NetworkCredential(PayerDetails.UserID, PayerDetails.Password);
httpRequest.ContentLength = SoapEnvelopeBytes.Length;
requestStream = httpRequest.GetRequestStream();
requestStream.Write(SoapEnvelopeBytes, 0, SoapEnvelopeBytes.Length);
requestStream.Close();
using (HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse())
{
StreamReader readStream = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
Response271 = readStream.ReadToEnd();
}
Decide if you want to send a SOAP1.1 or SOAP1.2 message.
For SOAP1.1 change this:
SoapEnvelope.Append("\"http://www.w3.org/2003/05/soap-envelope\"");
to this:
SoapEnvelope.Append("\"http://schemas.xmlsoap.org/soap/envelope/\"");
For SOAP1.2 change this:
httpRequest.ContentType = "text/xml;charset=UTF-8";
httpRequest.Headers.Add("SOAPAction", "EligXsdRealTimeTransaction");
to this:
httpRequest.ContentType = "application/soap+xml; charset=utf-8;action=EligXsdRealTimeTransaction";
I am trying to post SOAP Envelope directly to Dynamics NAV Webservices using HttpWebRequest, HttpWebResponse.
Code:
private void button1_Click(object sender, EventArgs e)
{
string requestString = LoadData();
HttpWebRequest request;
HttpWebResponse response = null;
string url = "http://localhost:7047/DynamicsNAV70/WS/Page/nav_Item";
byte[] requestBuffer = null;
Stream postStream = null;
Stream responseStream = null;
StreamReader responseReader = null;
request = (HttpWebRequest)WebRequest.Create(url);
request.ProtocolVersion = new Version(1,1);
request.Method = "POST";
//request.Headers.Add("SOAPAction", #"urn:microsoft-dynamics-schemas/page/nav_item:create");
request.Headers.Add("Action", #"urn:microsoft-dynamics-schemas/page/nav_item");
//request.Headers.Add("Content-Type", #"text/xml; charset=utf-8");
request.ContentType = #"application/xml; charset=utf-8";
requestBuffer = Encoding.ASCII.GetBytes(requestString);
request.ContentLength = requestBuffer.Length;
request.UseDefaultCredentials = true;
postStream = request.GetRequestStream();
postStream.Write(requestBuffer, 0, requestBuffer.Length);
postStream.Close();
response = (HttpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
string response_result=string.Empty;
if (responseStream != null)
{
responseReader = new StreamReader(responseStream);
response_result = responseReader.ReadToEnd();
}
MessageBox.Show(response_result);
}
private string LoadData()
{
// throw new NotImplementedException();
XmlDocument oCustomer = new XmlDocument();
oCustomer.Load(#"C:\Users\kishore.LOCAL.000\Desktop\NAV_DEMO\NAV_DEMO\bin\Debug\input\item.xml");
return oCustomer.InnerXml;
}
Format of SOAP Envelope is below:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ins="urn:microsoft-dynamics-schemas/page/nav_item">
<soapenv:Header/>
<soapenv:Body>
<ins:Create>
<ins:nav_Item>
<!--Optional:-->
<ins:Key>?</ins:Key>
<!--Optional:-->
<ins:No>1234</ins:No>
<!--Optional:-->
<ins:Description>Test Item</ins:Description>
</ins:nav_Item>
</ins:Create>
</soapenv:Body>
</soapenv:Envelope>
But when I am trying to get response without Header in HttpWebRequest, its returning whole web service in xml format with Status OK, but Item is not inserting in NAV.
When I am trying to get response with Header in HttpWebRequest, its {"The remote server returned an error: (500) Internal Server Error." System.Net.WebExceptionStatus.ProtocolError}
I want to create Item in NAV using soap envelope not by direct referencing the service.
Any help will helpful to me.
With Regards
Kishore K
It looks like you using SOAPui to create request xml. This app always adds invisible chars at the end of each line. Delete them.
Also try to unformat your request, e.g. make it in one line. For unknown reason Nav threats linebreake between certain tags as error (throws http 500). I just forgot which tags (header and body may be). The rest linebreaks are fine.
And SOAPAction header is mandatory so use it or you will get wsdl in response all the time.
P.s. beta of SOAPui works fine with Nav and supports NTLM so you can use it to test different request xml and find which format is correct.
I am new to using intergrating with nav web services, I am trying to send an xml request using a simple c# console application but it is always returning a 401(unauthorised)
static void Main(string[] args)
{
Console.WriteLine("We have started");
string pageName = "http://hrp-dmu.uganda.hrpsolutions.co.ug:9047/DynamicsNAV80/WS/Uganda%20Management%20Institute/Page/CustomerWS";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pageName);
req.Method = "POST";
req.ContentType = "text/xml;charset=UTF-8";
req.ProtocolVersion = new Version(1, 1);
req.Headers.Add("SOAPAction", #"urn:microsoftdynamicsschemas/page/customerws:Create");
Console.WriteLine("After preparing request object");
string xmlRequest = GetTextFromXMLFile("E:\\tst3.xml");
Console.WriteLine("xml request : "+xmlRequest);
byte[] reqBytes = new UTF8Encoding().GetBytes(xmlRequest);
req.ContentLength = reqBytes.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(reqBytes, 0, reqBytes.Length);
}
}
catch (Exception ex)
{
Console.WriteLine("GetRequestStreamException : " + ex.Message);
}
HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
Console.WriteLine("GetResponseException : " + exc.Message);
}
string xmlResponse = null;
if (resp == null)
{
Console.WriteLine("Null response");
}
else
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
xmlResponse = sr.ReadToEnd();
}
Console.WriteLine("The response");
Console.WriteLine(xmlResponse);
}
Console.ReadKey();
}
private static string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
I'm trying to make a SOAP request in C#. Using SoapUI, I have successfully made the required request, so I basically copied the request string into the LoadXml of the following C# code:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(#"https://w8cert.iconnectdata.com:443/FleetCreditWS/services/FleetCreditWS0200");
webRequest.Headers.Add(#"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(#"<?xml version=""1.0"" encoding=""utf-8"" ?><soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:main=""http://fleetCredit02.comdata.com/maintenance/"" xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">
<soapenv:Header>
<wsse:Security>
<wsse:UsernameToken>
<wsse:Username>{MyUserName}</wsse:Username>
<wsse:Password>{MyPassword}</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<main:ProprietaryIntradayRequest>
<startDate>2018-02-06</startDate>
<maskCardFlag>false</maskCardFlag>
</main:ProprietaryIntradayRequest>
</soapenv:Body>
</soapenv:Envelope>");
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
WebResponse response;
try
{
using (response = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
}
}
}
catch (WebException e)
{
StreamReader str = new StreamReader(e.Response.GetResponseStream());
System.Diagnostics.Debugger.Break();
}
This code throws the ever-fun (500) Internal Server Error on the "using (response = webRequest.GetResponse())" line. I even tried to capture the web exception response, but get the same 500 error.
Can anyone see something I'm missing that would cause the same request to work in SoapUI, but fail in C#?