HTTPWebRequest Response Error when sending SOAP - c#

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);

Related

Getting 400 (bad request) when trying to send a message to slack with webhook URL

I'm trying to send a message to a slack channel in C#. with http request, using Webhook url.
In the get response line' I'm getting 400- bad request.
My function:
public void SendSlackAlert(string message, string slackUrl)
{
try
{
var content = $"{{\r\n\"text\":\"{Context}\r\n{message} \"\r\n}}";
if (string.IsNullOrWhiteSpace(slackUrl))
{
return;
}
var httpRequest = WebRequest.Create(slackUrl) as HttpWebRequest;
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.Timeout = Convert.ToInt32(TimeSpan.FromDays(1).TotalMilliseconds);
var bytesToSend = Encoding.UTF8.GetBytes(content);
httpRequest.ContentType = "application/json;charset=utf-8";
httpRequest.ContentLength = bytesToSend.Length;
using (var requestStream = httpRequest.GetRequestStream())
requestStream.Write(bytesToSend, 0, bytesToSend.Length);
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
using (var responseReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
responseReader.ReadToEnd();
}
}
catch (Exception ex)
{
// return "Error";
}
}
I am transferred to catch with the error, in this line:
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
would greatly appreciate any attempt to help.
Thank you!
I saw elsewhere that having the encoding set can cause issues with the Slack API.
Instead of setting the Content-Type header along with an encoding, try only setting the Content-Type header to application JSON.
Replace this line:
httpRequest.ContentType = "application/json;charset=utf-8";
With this line:
httpRequest.Headers.Add(HttpRequestHeader.ContentType, "application/json");

Getting Unauthorized error on c# WebResponse response = request.GetResponse();

Im getting anauthorized error when doing a GET request on C# but if I try it using post man its returns just fine.
heres my c# code:
url = #"http://somesource.com/api/v10/" + url;
WebRequest request = WebRequest.Create(url);
request.Headers.Add("Authorization", "Token 3e68409924cc57ff07a8e29a18341fd99d3fba91ds");
request.Method = "GET";
request.Timeout = TimeO;
try {
WebResponse response = request.GetResponse();
status = ((HttpWebResponse)response).StatusDescription.ToString();
if (status != "OK")
Log.WriteLog(module, "Response x:: " + status);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
dataResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
} catch (WebException ex)
{
dataResponse = "{\"Error\":true,\"Update\":false,\"Msg\":\"RQ x:: " + ex.Message + "\"}";
Log.WriteLog(module, dataResponse);
}
it returns The remote server returned an error: (401) Unauthorized.
but when I try using the same url + header with Authorization = "Token 3e68409924cc57ff07a8e29a18341fd99d3fba91ds" on post man as GET request, it returns json data just fine.
although if I dont send the headers on postman i get
{
"detail": "Authentication credentials were not provided."
}
and if I intentionally set the token wrong, this is what I get:
{
"detail": "Invalid token."
}
different from what the c# program logs. which is
The remote server returned an error: (401) Unauthorized.
what could be the reason for this?
Thanks!
try the following code. original reference here
string url = #"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
WebRequest request = WebRequest.Create(url);
request.Credentials = GetCredential();
request.PreAuthenticate = true;
private CredentialCache GetCredential()
{
string url = #"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["ead_username"], ConfigurationManager.AppSettings["ead_password"]));
return credentialCache;
}

Post SOAP envelop to MS Dynamics NAV Web Service

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;
}

Internal Server Error (500) when doing SOAP request

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 ;)

SOAP Request Failure

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#?

Categories

Resources