I have generated stubs from a wsdl file in a asp.net web app. My question is how do i add those function calls to a httpwebrequest? I have gotten this far but dont know how to finish it off and send the soap off on the wire.
public HttpWebRequest CreateWebRequest(string webMethod)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("");
webRequest.Headers.Add(#"SOAPAction", "\"http://www.multispeak.org/Version_3.0/"+ webMethod +"\"");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
protected void Button1_Click(object sender, EventArgs e)
{
MR_ServerSoapClient soapClient = new MR_ServerSoapClient(endPoint,uri);
PingURLRequest request = new PingURLRequest();
PingURLResponse response = new PingURLResponse();
}
I am not sure why you would not use the client methods generated for you, but:
using (var response = (HttpWebResponse)webRequest.GetResponse())
{
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
}
Related
I am doing some testing for a Xamarin Android app with a simple local WCF service to prove my connection code works.
Service:
[OperationContract]
string Ping();
…
public string Ping()
{
return "Pong";
}
Test Code in Xamarin App:
var request = HttpWebRequest.Create(string.Format(#"http://192.168.1.175/_Services/TestService1.svc/Ping"));
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.ContentLength = 0; //pass.Length;
request.Method = "POST";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) //Errors out here
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
}
Error:
The remote server returned an error: (400) Bad Request.
Edit:
When using ServiceReference, the following works:
private void button3_Click(object sender, EventArgs e)
{
ServiceReference1.TestService1Client client = new ServiceReference1.TestService1Client();
string returnString;
returnString = client.Ping();
label1.Text = returnString;
}
Slightly different code still does not work:
private void button4_Click(object sender, EventArgs e)
{
//string serviceUrl = "http://192.168.1.175/_Services/TestService1.svc";
string serviceUrl = "http://localhost/_Services/TestService1.svc";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl + "/Ping"));
httpRequest.Accept = "text/xml";
httpRequest.ContentType = "text/xml";
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
httpRequest.KeepAlive = false;
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) //400 Bad Request
{
using (Stream stream = httpResponse.GetResponseStream())
{
label1.Text = (new StreamReader(stream)).ReadToEnd();
}
}
}
The answer was rooted in System.ServiceModel.Activation.WebServiceHostFactory
For some reason none of my sources mentioned this during research for using HttpWebRequest.
I found the reference by chance when looking at Android WCF consuming.
https://minafayek.wordpress.com/2013/04/02/consuming-iis-published-restful-wcf-service-from-android-over-wifi/
I got my testing programs working so, I should be able to move forward.
i am trying to create a cookie in a web service when testing this code it works when i call it from aspx page it return "Done" but the cookie is not created
[WebMethod]
public string CreateCookie()
{
var Cookies = new HttpCookie("test123");
Cookies.Value = "123";
Cookies.Expires = DateTime.Now.AddHours(1);
HttpContext.Current.Response.Cookies.Add(Cookies);
return "Done";
}
My Request
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost/testservice.asmx/CreateCookie");
myRequest.Method = "POST";
myRequest.ContentLength = 0;
HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
Response.Write(reader.ReadToEnd());
I've always done my web services in PHP. Now I'm trying some ASP.NET on a project and I found myself on a tricky situation. I have the following C# code, behaving as a "client"
public void sendRequest(string URL, string JSON)
{
ASCIIEncoding Encode = new ASCIIEncoding();
byte[] data = Encode.GetBytes(JSON);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
string responseText;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
responseText = reader.ReadToEnd();
}
returnRequestTxtBx.Text = responseText;
}
Well, now I want to handle on the ASPX.CS side...
my question is... how do I access the data I sent as a POST?
Is there a way in the "Page_Load" method that I can handle the JSON I sent?
To read post method data on your server side read HttpContext.Request.Form method:
protected void Page_Load(object sender, EventArgs e)
{
string value=Request.Form["keyName"];
}
Or if you want to access row body data simply read: Request.InputStream.
And if you want handle Json format consider Newtonsoft.Json packege.
All I want is to send xml data from C# desktop application to ASP.Net webpage.
My C# code look like this.
public string SendRequest()
{ string data = "<?xml version="1.0"?><author>Gambardella, Matthew</author>";
string _result;
Uri uri = new Uri("http://localhost:62511/Default");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "text/xml";
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
var response = (HttpWebResponse)request.GetResponse();
var streamResponse = response.GetResponseStream();
var streamRead = new StreamReader(streamResponse);
Console.Write(response.StatusCode);
_result = streamRead.ReadToEnd().Trim();
streamRead.Close();
streamResponse.Close();
response.Close();
return _result;
}
My ASP .Net Code looks like this
protected void Page_Load(object sender, EventArgs e)
{
using (var reader = new StreamReader(Request.InputStream))
{
string xml = reader.ReadToEnd();
labelsam.Text = xml;
}
....
}
labelsam is a label on web page.But I get nothin in labelsam.Is there anyway to check whether the data is received.Also whats wrong with code?
You have to specify content length for post method.
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength=data.Length; //ugly, but at least so
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
Good day to you all,
I wanted to ask you a simple question. What are the ways to call a soap web service from windows phone?
I have tried using the Service reference (I add service reference to a ?wsdl URL and it generates all the methods I have on web service), however I came across the error (unmarshalling error, unexpected elements) in sending the request. Just to note I have created a soap web service in Java and all of the methods are functioning and returning data, both in iOS application and in Android application, however I am struggling with this in windows phone.
I wanted to check some information of possibilities of calling and consuming a soap based web service in windows phone and examples if possible.
Thank you.
The method "Add Service Reference" always returns me following error:
Unmarshalling Error: unexpected element (uri:"http://webservicelocation.com/",local:"param1"). Expected elements are <{}param1>,<{}param2>,<{}param3>
You can use HttpWebRequest for calling a soap webservice.
Below code is used to do a currency converter which calls a soap based webservice.
Inside MainPage
ServiceConnection cs = new ServiceConnection();
Inside Constructor
string pXml = #"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:web=""http://www.webserviceX.NET/"">" +
"<soapenv:Header/><soapenv:Body><web:ConversionRate>" +
"<web:FromCurrency>" + "USD" + "</web:FromCurrency>" +
"<web:ToCurrency>" + "INR"+ "</web:ToCurrency>" +
"</web:ConversionRate></soapenv:Body></soapenv:Envelope>";
ServiceConnection cs = new ServiceConnection();
cs.OnEndResponse += new ServiceConnection.OnServerEndResponse(serviceConnection_OnEndResponse);
cs.ServiceCall(pXml);
After the service Call u will get response inside the function
void serviceConnection_OnEndResponse(string response, int statusCode)
{
MessageBox.Show(response);
}
Here is the class Service Connection
class ServiceConnection
{
public string url = "";
private string postXml;
public delegate void OnServerEndResponse(string response, int statusCode);
public event OnServerEndResponse OnEndResponse;
public ServiceConnection()
{
url = "http://www.webservicex.net/CurrencyConvertor.asmx";
}
public void ServiceCall(string pxml)
{
postXml = pxml;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = postXml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
OnEndResponse(Response, Convert.ToInt32(response.StatusCode));
});
}
catch
{
OnEndResponse("", 500);
}
}