WCF Rest service receives null value from SOAPUI - c#

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.

Related

Changing HTTP Request to HTTPS, message content seems to be lost

This is not a subject I am strong in so I apologize ahead of time if I say something ridiculous.
I have developed an HTTP service using Mule. I have it functioning perfectly when I connect directly to the service and send data using a test harness I wrote in C#.
As the final part of my testing, I need to send it to an HTTPS URL that is supposed to "decrypt" the message and forward it to my service. When I send a message to the HTTPS URL, it gets forwarded to my service but the message contents appear empty and therefore does not get processed. I understand that I may have to add some "encryption" to my Test Harness but I have been researching how to do this all day and nothing I have found is answering my question.
Here is an example of the code I am using for the simple HTTP request:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["HttpDestination"].ToString());
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
using (Stream strm = req.GetRequestStream())
{
strm.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
What do I need to change here to make this work?
Here is the solution that I discovered here. I needed to add the following line:
req.ProtocolVersion = System.Net.HttpVersion.Version10;
Without this, a timeout was occurring when getting the request stream and the content was never being sent, only the headers.

Accessing and getting response from API call

I am checking out the namecheap api and am having some difficulty getting started. I am trying to access the api after setting up the sandbox account etc and a sample response is in XML format:
<ApiResponse Status="OK" xmlns="http://api.namecheap.com/xml.response">
<Errors />
<Warnings />
<RequestedCommand>namecheap.domains.check</RequestedCommand>
<CommandResponse>
<DomainCheckResult Domain="google.com" Available="false" />
</CommandResponse>
<Server>WEB1-SANDBOX1</Server>
<GMTTimeDifference>--4:00</GMTTimeDifference>
<ExecutionTime>0.875</ExecutionTime>
</ApiResponse>
I know how to parse XML, but what I need a little guidance with is how do I get started with the actual request/response part of the API call.
I know which parameters I need to send, and I know I need the api key and url, but how do I write the WebRequest and WebResponse part of it? Or can Linq provide me a way to achieve that too?
I was trying to use:
WebRequest req = HttpWebRequest.Create(url + apikey + username + command + domain);
WebResponse response = req.GetResponse();
But I don't see a way to do anything with variable response.
How can I make a very simple API call to this API and get its response into XML format so I can parse it?
Any help at all is really appreciated.
You need to get the Response Stream associated and read from it:
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
Console.WriteLine ("Response stream received.");
Console.WriteLine (readStream.ReadToEnd ());
WebResponse is abstract, you must cast it to an HttpWebResponse.
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
You will then be able to access the various information inside that you're looking for.
Also, you might consider using a WebClient if you're just doing simple web requests, it's much easier to work with... literally as easy as:
string response = new WebClient().DownloadString("http://somewebsite.com/some/resource?params=123");

Passing XML document as an parameter to Web services using 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.

Consume Web Service with POST from a WCF Service

So this is my situation. I have to consume a third party web service (not wcf) from another WCF service that will serve as an intermediary between the first service and my web app. The problem is almost every example I have seen on doing this requieres you to Add Web/Service Reference to the app in order to generate the proxy, but I can't add the reference, it returns an error, possibly due to some authentication required.
This service can be consumed only by either GET or POST. I was successful in consuming the service by both GET and POST from an ajax call with jquery in a web page, but I don't know how to consume the service from inside a wcf service in c#.
An example GET request from the service is:
http://webservice.server.com/services/myservice?user=[username]&password=[password]&value1=[somevalue]&value2=[anothervalue]
The response is an xml with the status code of the operation and a status message, which I then proceed to save to a database.
How might I go about doing this?
Thank you for any help...
SOLUTION
Thanks to Sean for pointing me in the right direction. How I did it:
Reference article: How to use HttpWebRequest to send POST request to another web server
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=" + username;
postData += ("&password=" + password);
postData += ("&value1=" + val1);
postData += ("&value2=" + val2);
byte[] data = encoding.GetBytes(postData);
// Prepare POST web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(new Uri("http://webservice.server.com/services/myservice"));
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
// Get response
using (HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Read the whole contents and return as a string
result = reader.ReadToEnd();
}
XDocument doc = XDocument.Parse(result);
// Read XML
Please if you have any comments on my solution, objections or improvements, all comments are welcomed.
I think you'd want to take a look at the HttpRequest class:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.aspx
If you can't add the web service reference (I would investigate further why you can't do this first) I am afraid you'll have to do this manually issuing an HTTP Request manually using the WebClient class WebClient or the HttpReqest class as Sean suggests

.NET Web Service receive HTTP POST request (500) Internal Server Error

I am currently writing a C# web service which has several methods, one of which has to receive HTTP POST requests. The first thing i have done is alter the web.config file in the web service project as below.
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpPostLocalhost"/>
<add name="Documentation"/>
</protocols>
</webServices>
I can run the web service locally and when i click on the method in the browser, i can see it handles HTTP POST requests and accepts args=string, as my signature of the web method accepts one string parameter named args. I am then testing this via a test ASP.NET app using the code below to fire the HTTP POST request.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ConfigurationManager.AppSettings["PaymentHubURL"].ToString());
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
StringBuilder sb = new StringBuilder();
sb.Append("message_type=");
sb.Append(HttpUtility.UrlEncode("Txn_Response"));
byte[] bytes = UTF8Encoding.UTF8.GetBytes(sb.ToString());
request.ContentLength = bytes.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(bytes, 0, bytes.Length);
}
string test;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader reader = new StreamReader(response.GetResponseStream());
test = reader.ReadToEnd();
}
But when i run this i get "The remote server returned an error: (500) Internal Server Error". If i remove the parameter, by removing the stringbuilder and byte code, as well as having no parameter in the web service, it works. So it is obviously a problem with the parameters. I actually want to send more data, and was using a string[] parameter in the web service, but this also failed.
Can anyone help??
I would suggest that you reconsider your approach. Microsoft has written pretty awesome libraries for consuming web services, but there are two ways to do it - "add web reference" and "add service reference".
In your case, it seems you have an "asmx web service" so I would recommend that you add a "web reference" to you project in visual studio. This is assuming you are using visual studio.
After you add this web reference, you can create your client by "new"-ing it. You can the execute any web method on this client. This is the easiest way to consume web services. You do not have to deal with any http complications.
Hope this helps.
I can guess you are building the HttpPost request wrongly.
Try to use the code showed at the link below to create your request:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
Or probabily the response doesn't contain unicode char value
try to copy and paste this code to get the response
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader objSR;
webResponse = (HttpWebResponse)response.GetResponse();
StreamReader reader = webResponse.GetResponseStream();
objSR = new StreamReader(objStream, encode, true);
sResponse = objSR.ReadToEnd();

Categories