Unable to Pass Image in HTTP POST in a HTTP Web Request in ASP.NET - 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

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();

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

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>

How to do httpPost to a webservice which accepts a byte array of a file using c#

I am working on an API kind of project,
I have wrote a WebMethod (not exactly. I am using MVC to create REST like API)
public UploadFileImage(string employeeId, byte[] imageBytes, string imageName)
{
// saves the imagebyte as an image to a folder
}
the web service would be consumed by a web app, or windows or even iphone or such portable stuffs. I am testing my web service using a web app, by simple httpPost.
string Post(Uri RequestUri, string Data)
{
try
{
HttpWebRequest request = HttpWebRequest.Create(RequestUri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = IsXml.Checked ? "text/xml" : "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes(Data);
Stream os = null; // send the Post
request.ContentLength = bytes.Length; //Count bytes to send
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
return streamReader.ReadToEnd();
}
catch (Exception ex)
{
return ex.Message;
}
}
This code works fine for evey method like, AddEmployee, DeleteEmployee etc. THe parameter Data is of form "Id=123&name=abcdefgh&desig=Developer",
How I call any other function is
Post(new Uri("http://localhost/addemployee"),"name=abcd&password=efgh")
where post is the function i wrote.
All good for all functions. Except that I dont know how to consume the above mentioned function UploadFileImage to upload an image?
Thanks
Try encoding the imageBytes as Base64.
From your code snippet is not too clear how you call UploadFileImage, that is how you convert its parameters tripplet into Data.
That is why my answer is quite generic:
In general, you'd better transfer your image file by
request.ContentType = "multipart/form-data; boundary=----------------------------" + DateTime.Now.Ticks.ToString("x");
Please allow me to refer you to a sample at StackOverflow on how to format a multipart request. I am sure that if you google, you shall find a lots of detailed examples and explanations as well.
I hope this helps :-)

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;
};

How to submit a form automatically using HttpWebResponse

I am looking for an application that can do the following
a) Programmatically auto login to a page(login.asxp) using HttpWebResponse by using already specified username and password.
b) Detect the redirect URL if the login is successful.
c) Submit another form (settings.aspx) to update certain fields in the database.
The required coding needs to be using asp.net
The application needs to complete this entire process in the same session cookie.
string sUrl = "login.aspx";
HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create(sUrl);
CookieContainer oMyCookies = new CookieContainer();
oRequest.CookieContainer = oMyCookies;
// encode postdata into byte array. the postdata string format will most likely be different and you'll have to examine the postdata going back and forth using some firefox addon like LiveHTTPHeaders
byte[] oPostData = System.Encoding.UTF8.GetBytes("username=" + HttpUtility.UrlEncode(sUser) + "&pass=" HttpUtility.UrlEncode(sPass));
using (Stream oStream = oRequest.GetRequestStream())
{
oStream.Write(oPostData, 0, oPostData.Length);
}
HttpWebResponse oResponse = oRequest.GetResponse();
// save response cookies in our cookie object for future sessions!
foreach (Cookie oCookie in oResponse.Cookies)
{
oMyCookies.SetCookies(sUrl, oCookie.ToString());
}
// maybe check response headers for location
string sResponseContents = null;
using (StreamReader oReader = new StreamReader(oResponse.GetResponseStream())
{
// store server response into string
sResponseContents = oReader.ReadToEnd();
}
...this is the basic code required for what you want to do.

Resources