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
Related
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.
I have this class that works correctly from a console application.
When I incorporate it into my Xamarin Forms project, it gives an error (refused connection) when creating the webrequest.
I would appreciate any help in that regard.
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
stays dead until causing an exception in Xamarin forms.
Error image
My code:
public class WebServiceSOAP
{
var _url = "http://MyDomain/My.asmx";
var _action = "http://MyDomain/MyMethod";
string sxml = #"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:adh=""http://Mydomain"">
<soapenv:Header/>
<soapenv:Body>
<adh:MyMethod>
<adh:param1>TEST1</adh:param1>
<adh:param2>test2</adh:param2>
<adh:param3>test3</adh:param3>
</adh:MyMethod>
</soapenv:Body>
</soapenv:Envelope>";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(sxml);
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
using (var response = (HttpWebResponse)(webRequest.GetResponse()))
{
HttpStatusCode code = response.StatusCode;
if (code == HttpStatusCode.OK) {
using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string resp = sr.ReadToEnd();
}
}
}
}
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 XmlDocument CreateSoapEnvelope(string sxml)
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
soapEnvelopeDocument.LoadXml(sxml);
return soapEnvelopeDocument;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
I use this following code, to connect huawei hilink, but it always returns an error.
First I get the token and session via
http://192.168.8.1/api/webserver/SesTokInfo
Can you please help me fix the issue?
string resulta = PostAndGetHTML("http://192.168.8.1/api/webserver/SesTokInfo");
string tok = resulta.Substring(57, 32);
string ses = resulta.Substring(108, 128);
Postxml("http://192.168.8.1/api/user/login", tok, ses);
public string PostAndGetHTML(string targetURL)
{
string html = string.Empty;
string url = targetURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
return html;
}
public void Postxml(string destinationUrl, string token, string ses)
{
var client = new RestClient();
string rawXml = #"<?xml version=""1.0"" encoding=""utf-8""?><request><Username>admin</Username><Password>" + Base64Encode("admin") + #"</Password></request>";
client.BaseUrl = new Uri(destinationUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("__RequestVerificationToken", token);
request.AddCookie("cookie",ses);
request.Timeout = 3000;
request.ReadWriteTimeout = 3000;
request.AddParameter("text/html", rawXml, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
}
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;
}
}
I have written a RESFful service for a phone app.
I am not sure what am I doing wrong? I tried to test it with multiple content type settings but no luck.
The data from a phone app is coming encoded in following format.
PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGU+ aGVyVmFsdWU+PC94ZW5jOkNpcGhlckRhdGE+PC94ZW5jOkVuY3J5cHRlZERhdGE+PC9zYW1sOkVuY3J5cHRlZEFzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==";
This is the definition in the interface:
[OperationContract]
[WebInvoke]
String GetUserInfo(String authenticateRequest);
I get error: with following test code.
'Unable to deserialize XML body with root name 'Binary' and root namespace '' (for operation 'GetMobileCheckCapture' and contract ('IMobileCC', 'http://tempuri.org/')) using DataContractSerializer
This is how I am trying to test the service:
String encryptedSAML =
PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGU+ aGVyVmFsdWU+PC94ZW5jOkNpcGhlckRhdGE+PC94ZW5jOkVuY3J5cHRlZERhdGE+PC9zYW1sOkVuY3J5cHRlZEFzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==";
HttpWebRequest req = WebRequest.Create("http://localhost/Services/Mservice.svc/GetUserInfo") as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml; encoding='utf-8'";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bDataToPass = encoding.GetBytes(encryptedSAML);
req.ContentLength = bDataToPass.Length;
using (Stream dataStream = req.GetRequestStream())
{
dataStream.Write(bDataToPass, 0, bDataToPass.Length);
}
try
{
using (WebResponse webresponse = req.GetResponse())
{
StreamReader reader = null;
string responses = "";
string StatusDescription = ((HttpWebResponse)webresponse).StatusDescription;
if (((HttpWebResponse)webresponse).StatusCode != HttpStatusCode.OK)
{
// Console.Write();
}
reader = new StreamReader(webresponse.GetResponseStream());
responses = reader.ReadToEnd();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(responses.Replace("&", "&"));
response = xmldoc;
}
}
catch (WebException e)
{
using (WebResponse response2 = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response2;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response2.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
Console.WriteLine(text);
}
}
}
Have you tried to use UTF-8 encoding instead of ASCII?
HttpWebRequest req = WebRequest.Create("http://localhost/Services/Mservice.svc/GetUserInfo") as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml; encoding='utf-8'";
UTF8Encoding encoding = new UTF8Encoding();
byte[] bDataToPass = encoding.GetBytes(encryptedSAML);
req.ContentLength = bDataToPass.Length;