The remote server returned an error: (400) Bad Request while consuming a WCF Service - asp.net

Please view the code given below. While the debug reaches the request.GetResponse() statement the error has been thrown.
Uri uri = new Uri(address);
string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>";
data.Replace("'", "\"");
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
if (uri.Scheme == Uri.UriSchemeHttps)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";// WebRequestMethods.Http.Post;
request.ContentLength = byteData.Length;
request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8";
//request.ContentType = "application/x-www-form-urlencoded";
//Stream requestStream = request.GetRequestStream();
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteData, 0, byteData.Length);
}
//writer.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
Response.Close();
Response.Write(tmp);
}

I would double check the URL. If the URL looks ok on the client side, I recommend looking at access logs on your server to see what URL is being hit. 4xx errors mean a resource was not found. If the endpoint was correct, but the request was fubared, you would get a 5xx error code. (Assuming that your server side frameworks uses standard HTTP Response Codes).

As has been mentioned you should use the 'Add Service Reference' to access the WCF service from a .NET client. However, if you're emulating trying to connect from a non .NET client, your soap envelope is missing the header information.
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
specify your action namespace here (e.g. http://tempuri.org/ISomeService/Execute)
</Action>
</s:Header>

Related

can a MVC 3 app execute an Action in a different app on the same server

I have two asp.net applications running on one server, one is MVC-3, the other is not. the MVC application has a POST action which sends an email and returns a JSON object. Can the plain asp.net application somehow execute the action (from server) and receive the JSON object? I guess it just needs to execute a POST somehow?
Found the answer: It is the method HttpWebRequest, used as follows.
string data = "data to post";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("put URL here");
// set post headers
request.Method = "POST";
request.KeepAlive = true;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
System.IO.StreamWriter writer = new System.IO.StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
writer.Dispose();
// next line posts the data to the URL
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Consuming REST Service pb

I'm having some problem consuming REST Service and want to figure out what I'm missing in implementation.
https://<server-name-or-address>/api/sessions
if I call this rest api using cURL, it works just fine by following script
curl -i -k -H "Accept:application/*+xml;version=1.5" -u username:password -X POST https://<server-name-or-address>/api/sessions
However, it isn't working at all with C# asp.net. I'm not sure what I'm missing here. Here are my attempts:
1) Using HTTP Web Request
Uri address = new Uri(url);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/*+xml;version=1.5";
request.Credentials = new NetworkCredential(username,password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// following exception fires on calling aforementioned statement
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
2) Using Hammock.net
Hammock.RestClient client = new Hammock.RestClient();
string encodedAPIKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
client.AddHeader("Accept", "application/*+xml;version=1.5");
client.AddHeader("Authorization", "Basic " + username + ":" + password);
client.Authority = url;
Hammock.RestRequest req = new Hammock.RestRequest();
req.Path = url;
Hammock.RestResponse response = client.Request(req);
string _result = client.Request(req).Content; // exception
3) Using RestSharp
string _loginInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
RestSharp.RestClient client = new RestSharp.RestClient();
client.AddDefaultHeader("Accept", "application/*+xml;version=1.5");
client.AddDefaultHeader("Authorization", "Basic " + _loginInfo);
client.BaseUrl = url;
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.AddUrlSegment("method", "POST");
request.AddUrlSegment("uri", url);
string result = client.Execute(request).Content;
I also have tried with HttpClient, WebRequest, WebClient though nothing appears to work.
Try manually setting the Authorization header yourself in the HTTP request.
string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
request.Headers.Add("Authorization", authorization);
EDIT:
It looks as though it may be due to a self-signed, expired, or otherwise invalid cert. Try the following
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Gleaned from this SO: https://stackoverflow.com/questions/5595049/servicepointmanager-servercertificatevalidationcallback-question

Unable to Pass Image in HTTP POST in a HTTP Web Request in ASP.NET

I am having trouble converting an image into bytes and saving it in database.
Here is the description,
I have an image that will be send from a remote device to the web server using HTTP POST.
so what I am doing is I ask them to sent the image to me.
Since the data is sent in POST i assume they will send me the Bytes by converting the bytes into string using
byte[] img = FileUpload1.FileBytes;
Encoding enc = Encoding.ASCII;
string img = enc.GetString(img);
Then they make a WebRequest using HTTPWebRequest and append this image in HTTP POST.
The Whole Code for making the request ---
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
//Create the POST Data
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
imgByte = imgUpload.FileBytes;
}
string imgPh = null;
Encoding enc = Encoding.ASCII;
if (imgByte != null)
{
imgPh = enc.GetString(imgByte);
}
string postData = "sid=8062BD53EB4552AD6D0FBB7E5DC5B7AF&status=Y&uid=123456789012&fname=Dinesh Singh&lname=Malik&ftname=Balwan&yrbirth=1988&gender=Male&address1=Address1&address2=Address2&address3=Address3&address4=Address4&imagePh=" + imgPh;
byte[] post = Encoding.UTF8.GetBytes(postData);
//Set the Content Type
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = post.Length;
Stream reqdataStream = request.GetRequestStream();
// Write the data to the request stream.
reqdataStream.Write(post, 0, post.Length);
reqdataStream.Close();
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
// Get the response.
response = request.GetResponse();
}
catch (Exception ex)
{
Response.Write("Error Occured.");
}
On the Page to which Request is made I am getting this image again into bytes using
Encoding enc = Encoding.ASCII;
byte[] imagePhoto = enc.GetBytes(postData["imageph"]);
From Here I save it into my Database
But when I retrieve the image using the Handler, it does not show the image.
The issue is the conversion of the image from byte[] to string and then converting string into byte[] at the Web Server. (Because when I save the image directly without this conversion using TestPage on server it shows the image.)
So What am I doing wrong in this.
Also is there any way in the above code to get the data of HTTP Post as received by the Web Server (retrieve HTTP Headers).
I want to retrieve this data received to sent it back to the Other Development to develop the request at the device in the same format as I am receiving in the HTTP Web Request URL
Any help would be appreciated.
Ok I think finally I figured it out.
What I did was -
Image -> byte[] -> Convert.ToBase64String -> Append The String Data to Post Request
At the Server-
Get the Post Data -> Convert.FromBase64String -> byte[] -> Insert into Database
Works Great...:)
Thanks

How do I get responseText when server sends 500 error on WebRequest.Create(URL).GetResponse()

I am calling a json web service that sends error messages by setting StatusCode to 500 and then sending error message as response text (such as { "Message": "InvalidUserName" } ).
Problem is that ASP.NET does not give me the response text if web service sends statuscode 500.
try
{
WebRequest request = WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string result = streamReader.ReadToEnd();
streamReader.Close();
response.Close();
return result;
}
catch (Exception e)
{
// If web service sends 500 error code then we end up here.
// But there is no way to get response text :-(
}
Is there a way to solve this? Also: I am controlling the web service, so it might be a solution to do some change their. (Note: I need to call the service using plain WebRequest stuff - in this case it will not work with other methods such as adding as WebReference etc)
Any ideas?
Catch WebException instead. It has a Response property containing the response. Be sure to check for null before using it.

How to send a xml file over HTTP and HTTPS protocol and get result back

i want to send xml file with userid and password over HTTPs and then send all other xml file on HTTP using POST method and get the response as a xml file back. in ASP.NET (with vb.net preferred)
The url to which i want to send my xml file is:http://www.hostelspoint.com/xml/xml.php
exect xml file pettern is:
<?xml version="1.0" encoding="UTF-8"?>
<OTA_PingRQ xmlns="http://www.opentravel.org/OTA/2003/05"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_PingRQ.xsd"
TimeStamp="2003-03-17T11:09:47-05:00"
Target="Production" Version="1.001" PrimaryLangID="en"
EchoToken="testtoken12">
<EchoData>Hello</EchoData>
</OTA_PingRQ>
You should check out the WCF REST Starter Kit, and watch the screencast on HTTP Plain XML (POX) Services which explains step by step how to do just that - create a WCF REST service that will accept and process a plain XML stream.
All the WCF and WCF REST screencasts by Pluralsight are highly recommended! It's excellent material on how to get started and work with WCF.
In addition to that, the MSDN WCF Developer Center is your first point of contact for any questions or more information on WCF and WCF REST.
i don't know why u removed correct answer from here but yesterday i got correct answer here. and it is:- (can any one tell me how to do same with HTTPS protocol?)
string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\myfile.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}
Yes, you can do same thing using HTTPS protocol. You have to add this code before request:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
//
// policy code here ...
//
return validationResult;
};

Resources