Passing XML document as an parameter to Web services using C# - c#

I have to sent the XML document as an parameter to request an WebRequest using the Post method and get response. Web service implements the following method:
public string Register(XmlDocument register){...}
I'm trying doing like this , but I can't get response and I'm not sure that my code is working =(
HttpWebRequest request = HttpWebRequest.Create("http://ws2.sti.gov.kg/TRKService/PatentService.asmx/Register") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
Encoding ex = Encoding.GetEncoding("iso-8859-1");
XmlDocument doc = new XmlDocument();
doc.LoadXml("<foo><bar>baz</bar></foo>");
string rawXml = doc.OuterXml;
string requestText = string.Format("register={0}", HttpUtility.UrlEncode(rawXml, ex));
Stream requestStream = request.GetRequestStream();
StreamWriter requestWriter = new StreamWriter(requestStream, ex);
requestWriter.Write(requestText);
requestWriter.Close();
Maybe someone has a working example?

403 Error
If your getting a 403 when trying to import the web service this may not be your fault. Try
looking at the wsdl file in your web browser. If you still get the 403 error then their is no use coding any further because you don't have permission to use that service.
Code Syntax
Also, in your code I it appears your not reading back the response anywhere. Your last statement writes the XML to the stream but your not reading back the response anywhere.
requestWriter.Write(requestText);
requestWriter.Close();
SOAP
If the web service your are communicating with is SOAP based then your XML payload needs to conform to the SOAP standard. Your sample code above uses very basic XML, probably because it's just an example, but for it to work you will need requests with a format along the lines of
<?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>
<GetWeather xmlns="http://www.webserviceX.NET">
<CityName>string</CityName>
<CountryName>string</CountryName>
</GetWeather>
</soap:Body>
</soap:Envelope>
Not
<foo><bar>baz</bar></foo>
Again, you've obviously only used foo for an example but this could also be the source of your problem so inspect the actual XML payload you are sending.

Related

Sending a SOAP request to a web service using C#?

I am new to C# and my supervisor wants me to send a SOAP request to a web service and receive the connection string in C#. I have worked with Python before but I am really confused as how to do it in C#. This is the Python code I wrote. I am really lost.
import requests
url="http://172.20.3.3:8250/GS/GetConnectionStrings.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?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>
<DatabaseConnectionString xmlns='http://tempuri.org/'>
<DatabaseName>LMA</DatabaseName>
</DatabaseConnectionString>
</soap:Body>
</soap:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
I need to convert the above code to C#.

Send SOAP document to API endpoint

I am looking to send a SOAP document to an API.
The method I want to use is to create a c# object that reflects the soap document and then convert this object to a string before using this
string as content in my HTTPContent object that I send using a HTTPClient PostAsync Method.
The structure of the SOAP document is as follows :-
<SOAPENV:Envelope
xmlns:SOAPENV="http://www.w3.org/2003/05/soap-envelope"
xmlns:SOAPENC="http://www.w3.org/2003/05/soap-encoding"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAPENV:Body>
<StateRequest>
<SourceSystem>SOURCESYSTEMHERE</SourceSystem>
<SourcePassword>SOURCEPASSWORDHERE</SourcePassword>
<SourceJobList>
<SourceJobID>SOURCEJOBIDHERE</SourceJobID>
</SourceJobList>
</StateRequest>
</SOAPENV:Body>
</SOAPENV:Envelope>
I want to do something like the Psuedo code below:-
HttpContent content = new StringContent(object.ToString(), Encoding.UTF8, "text/xml");
content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
var response = _client.PostAsync(new Uri("http://targeturl.com "), content).Result;
What I want to know is
What c# object and attributes do I need to create to map this document structure? I need to create a C# object as I will be using data sent from
another source to update the SourceSystem,SourcePassword and SourceJobID properties.
What serialization/configuration do i need as part of the above method as I'm sure there is more required than just doing .ToString() on object.
Regards
Macca

WCF Rest service receives null value from SOAPUI

I am trying to test my wcf rest serice via soapui in my development environment, although my service is being hit but the parameter always receives null value.
I am passing string xml from SOAPUI using POST method but I always get null in xmlString argument of the XMLData method.I tried various combinations in the SOAPUI but everytime I receive a null value.
My intention is to send the xml parameter to another service in intranet.
Here's my Service Interface
[ServiceContract]
public interface IPayGService
{
[OperationContract]
[WebInvoke(Method="POST",RequestFormat=WebMessageFormat.Xml,ResponseFormat=WebMessageFormat.Xml,BodyStyle=WebMessageBodyStyle.Bare,UriTemplate="XMLData")]
void XMLData(string xmlString);
}
Here's the implementation of the above service contract
public class PayGService : IPayGService
{
public void XMLData(string xmlString)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://10.77.146.113:8081/PAGUIManager/rest/response");
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(xmlString);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
}
}
}
Here's what I'm trying to post from SOAP UI "<![CDATA[<response> <requestType>CC</requestType><pagTransId>CSS1234</pagTransId> <pgTransId>PG12345</pgTransId><amount>1200</amount><Status>SUCCESS</Status> <message>Payment Successful</message><MSISDIN>8888853991</MSISDIN><bankRef>123bank</bankRef> <bankCode>123</bankCode><checkSum>%%%%%%%^^^^&&& </checkSum> <cartInfo>8888853991:001:100</cartInfo></response>]]"
Here's the SOAPUI Snapshot
Hope this solution will help you:
In the Request Properties panel, there is option Max Size, if you set this to, lets say, 1048576 (1MB), SoapUI won't load more than 1MB of result into memory.
If you use this with Dump File property in the same panel, you can easily dump complete response to the file, thus avoiding memory usage.
Most likely the problem is not with the service itself, but with what SoapUI is sending.
I made a small test service with the same OperationContract as in your question. Then I create a project in SoapUI to test it. This raw xml works when sending it from SoapUI:
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:XMLData>
<tem:xmlString><![CDATA[<response> <requestType>CC</requestType><pagTransId>CSS1234</pagTransId> <pgTransId>PG12345</pgTransId><amount>1200</amount><Status>SUCCESS</Status> <message>Payment Successful</message><MSISDIN>8888853991</MSISDIN><bankRef>123bank</bankRef> <bankCode>123</bankCode><checkSum>%%%%%%%^^^^&&& </checkSum> <cartInfo>8888853991:001:100</cartInfo></response>]]></tem:xmlString>
</tem:XMLData>
</soapenv:Body>
</soapenv:Envelope>
My SoapUI is an older version than yours, so I don't know exactly where you should test raw xml. But I could see a Raw tab in your screenshot, so maybe that would be the place. You may have to change the tem namespace so it matches with the namespace you have on the service.

How do I call httpwebrequest c# .net

I am trying to learn how to use proxies..
My main goal is to be able to input a proxy adress in a text box and use that input as an actual proxy adress for the webBrowser in c#
But first what I need to figure out is how do I call the httpwebrequest?
I was looking at this question and the answers below and I was trying to follow along but when ever I try to use the httpwebrequest it doesnt even pop up in intellisense.
Im refering to this line right here
HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
how to use http post with proxy support in c#
Here is my code in button click calls HttpWebRequest that redirects to google home page that you can get either XML or HTML and you can also redirects to page.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.co.in");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Get response as stream from httpwebresponse
StreamReader resStream = new StreamReader(response.GetResponseStream());
//Create instance for xml document
XmlDocument doc = new XmlDocument();
//Load response stream in to xml result
xmlResult = resStream.ReadToEnd();
//Load xmlResult variable value into xml documnet
doc.LoadXml(xmlResult);
Please refer this image 1 and snapshot2

Getting MIME type from Web Service Response header

I invoke a web service provided by an external partner company. The web service returns files (.pdf, .dox, .png, ...) as a byte array.
If I would need to get the Header information (in detail I am interested in the content-type data) from the code, how can I get this information?
On our side, we are using VS 2010 and C# as language.
Here the code:
var client = new PublicService();
wsRequest request = new wsRequest();
var docInfo = new documentInfo();
docInfo.documentId = HSdocumentID;
docInfo.position = 1;
request.documentInfos = { docInfo };
byte[] doc = client.deliver(deliverRequest); //returns the file as byte array
The RESPONSE header would look like:
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body><ns2:deliverResponse xmlns:ns2="http://www.dalle.com/webservices/record/2012a">
<return>
<Include xmlns="http://www.w3.org/2004/08/xop/include"
href="cid:d3a#example.jaxws.sun.com"/>
</return></ns2:deliverResponse></S:Body></S:Envelope>
Content-Id: <d3a#example.jaxws.sun.com>
Content-Transfer-Encoding: binary
Content-Type: application/pdf <-- THIS IS THE INFO I NEED TO GET
Check out if there are SOAP headers on the Web Method call that answer your question
On the web method I do not have any properties/attributes that refer to the header. Is there a general way to get the Response header or is the web service that should provide features to get it?
(I provided an answer, rather than a comment, due to the code to be copied)

Categories