401 error when invoking asp.net service from c# - c#

I've been stuck on this for quite a bit, I keep getting a 401 error when calling an asp.net web service from c# server side code. Web service is hosted on a remote server, I get its address from config file (Wrapper Service). Whenever I call it, I get a 401 error, even though I can invoke web service method from web browser. Here's the code:
private string getCode(string name)
{
XmlDocument xmlResponse = new XmlDocument();
string request = getRequestXML(name);
string response = ExecuteRequest(request);
if (response != "")
{
xmlResponse.LoadXml(ExecuteRequest(request));
return xmlResponse.GetElementsByTagName("roaming")[0].InnerText;
}
else
{
return "error getting password";
}
}
private string getRequestXML(string userName)
{
var sr = "<?xml version='1.0' encoding='utf-8'?>"+
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"+
"<soap:Body>"+
"<GetAccountInfo xmlns='http://tempuri.org/'>"+
"<loginName>"+userName+"</loginName>"+
"</GetAccountInfo>"+
"</soap:Body>"+
"</soap:Envelope>";
return sr;
}
private string ExecuteRequest(string soapStr)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["WraperService"]);
req.Headers.Add("SOAPAction", "\"http://tempuri.org/" + "GetAccountInfo" + "\"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soapStr);
}
}
using (StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream()))
{
string result = responseReader.ReadToEnd();
//XDocument ResultXML = XDocument.Parse(result);
return result;
}
}

Related

The remote server returned an error: (405) Method Not Allowed service request and "Request method 'POST' not supported"

I have service client application written in C# where I create a service request as a soap XML as following:
var _url = "http://localhost:8082/tartsend";
var _action = "http://rep.oio.no/getTest";
StartSend startSend = new tartSend();
Envelope soapEnvelopeXml = StartSend.StartSendMethod();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
return soapEnvelopeDocument;
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static void InsertSoapEnvelopeIntoWebRequest(Envelope soapEnvelopeXml,
HttpWebRequest webRequest)
{
var xmlString = string.Empty;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Envelope));
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
"//Sendservice.xml";
System.IO.FileStream file = System.IO.File.Create(path);
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(file, soapEnvelopeXml);
xmlString = textWriter.ToString();
}
Console.WriteLine(xmlString);
}
Envelop is the class object that contains the Body, Header, and the other objects/ attributes. I serialize it in "InsertSoapEnvelopeIntoWebRequest" method and send it to the service side.
the server side is a simple method that suppose to send OK as response and nothing else. The server side service code is in jave spring boot as following:-
#SpringBootApplication
#EnableWebMvc
#RestController
public class TestController {
#RequestMapping(value = "/getslutsend", method=RequestMethod.GET,
consumes={MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE})
public ResponseEntity<?> readFromtest(#RequestBody String test) {
return new ResponseEntity<String>(HttpStatus.OK);
}
public static void main(String[] args) {
SpringApplication.run(TestController.class, args);
}
}
I'm not sure what I'm doing wrong to get the above errors mentioned in the title of this post. I get " (405) Method Not Allowed" and Request method not supported.
You have the RequestMethod.GET in your request mapping and the #RequestBody in parameter annotation.
Normally, you should avoid this combination, please use either RequestMethod.POST with #RequestBody, or RequestMethod.GET without the #RequestBody.

The remote server returned an error: (500) Internal Server Error. - SSIS Web Service Call

---------SSIS Script task Failing---------
I have this method in SSIS Script task which calls a web services but in response, I am getting The remote server returned an error: (500) Internal Server Error.
There is nothing else in the stack trace. When I use the same XML request in a Soap UI I get a valid response. In Soap UI I use Basic Authentication.
Can anyone help me out here. What could be the issue here?
public void GetWebServiceData(DataRow row)
{
FileInfo MyFileinfo = new FileInfo(configuration_file_location + "\\Test1\\Test.xml");
using (StreamReader myReader = MyFileinfo.OpenText())
{
myXmlMessage = myReader.ReadToEnd();
}
try
{
myXmlMessage = AddContractToXml(policyNumber, myXmlMessage);
int timeout = 1800000;
HttpWebRequest req = WebRequest.Create(new Uri(web_service_url))
as HttpWebRequest;
req.Method = "POST";
req.ContentType = "text/xml;charset=UTF-8";
byte[] formData = UTF8Encoding.UTF8.GetBytes(myXmlMessage.ToString());
req.ContentLength = formData.Length;
req.Timeout = timeout;
ICredentials credentials = new NetworkCredential(user_name, user_password);
WebProxy myProxy = new WebProxy(proxy_server, proxy_port);
req.Proxy = myProxy;
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
req.Credentials = credentials;
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
using (HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
using (StreamReader reader =
new StreamReader(resp.GetResponseStream()))
{
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.Load(reader);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
/* loading XSLT */
myXslTrans.Load(configuration_file_location + "\\Test1\\TestMonitoring.xslt");
/* creating Output Stream */
XmlTextWriter myWriter = new XmlTextWriter(web_service_output_transform_location + policyNumber + ".xml", null);
/* XML transformation */
myXslTrans.Transform(myXmlDoc, null, myWriter);
myWriter.Close();
}
}
}
catch (WebException webExcp)
{
string exMessage = webExcp.Message;
if (webExcp.Response != null)
{
using (StreamReader responseReader = new StreamReader(webExcp.Response.GetResponseStream()))
{
exMessage = responseReader.ReadToEnd();
if (!Directory.Exists(log_location + DateTime.Now.ToString("ddMMyyyy")))
Directory.CreateDirectory(log_location + DateTime.Now.ToString("ddMMyyyy"));
FileStream file = new FileStream(log_location + "//" + DateTime.Now.ToString("ddMMyyyy") + "//" + policyNumber + ".xml", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(file);
writer.Write(exMessage);
writer.Close();
file.Close();
}
}
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
catch (Exception e)
{
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
finally
{
}
}

Soap Web request is failing

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

Error 403: Forbidden when trying to make a POST API call

I have a Dot Net application, built with C# and MVC. I have to use a SOAPUI API, but I'm getting an error 403 when trying to perform this, even though I have access to a P12 certificate and its password. I've pasted the code below, having skipped any unimportant parts.
public string anotherPostDataAttempt()
{
try
{
X509Certificate2 cert = new X509Certificate2
(#"C:\Users\...\Visual Studio 2015\Projects\...\certificateFile.P12", "thisIsThePassword");
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(True);
string url = "https://...";
//HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
string xmlString = "";
StreamReader f_read = new StreamReader(#"C:\Users\...\Desktop\testFile.xml");
xmlString = f_read.ReadToEnd();
f_read.Close();
string DataToPost = xmlString;
String result = "";
String strPost = "RequestXML=" + DataToPost;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
//objRequest.ContentType = "text/xml; charset=utf-8";
objRequest.ContentType = "application/x-www-form-urlencoded";
//objRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
objRequest.ClientCertificates.Add(cert);
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
//
}
finally
{
myWriter.Close();
}
//The program crashes on the line below
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
catch (Exception ex)
{
throw ex;
}
}
For the record, I've already consulted this blog post in the subject matter but I'm guessing I must be doing something wrong after all, or I wouldn't be getting this error.
Full error:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
InnerException: Null.
Message: The remote server returned an error: (403) Forbidden.

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

Categories

Resources