I'm sure it's a common question, and I probably find solutions to this but I didn't understand them. Besides I'm doing this completely blind. Another point is: I don't want to use third party libraries.
I need to send an image from my Android app to my server via c# rest webservice.
I watched this method to convert the bitmap to a byte[].
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 0, outputStream);
return outputStream.toByteArray();
}
And here I have two (at least) problems:
How to send it as JSON? I tried Base64.encode() with COMMON and URLSAFE (or something like that) flags and I get error at server side: Not a valid Base64.
Then I suppose the client side it's ok, so how do I manage to receive and process the byte[]? Now it seems it try to convert automatically and it fails, maybe because client sends invalid data or well... I don't know.
I can't provide code right now (in fact I think I don't have code to do this at all), but I'll update with what I have if required.
Thanks and sorry for this horrible made question
Android :
byte[] content = getBitmapAsByteArray(bitmap);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new ByteArrayEntity(content));
HttpResponse response = httpClient.execute(httpPost);
c#.net
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
Related
I am having problems getting the X-Hub-Signature sent to me by facebook to match the one I am generating in C#. For a while I thought I was running the function wrong but I have now used multiple code sources on Stack Overflow and a website (http://billatnapier.com/security01.aspx) to confirm I am indeed creating the SHA-1 correctly.
So .... something is clearly wrong with the content. I am using ASP.NET Web API and the "Payload" that I am using to feed into the SHA-1 algorithm is the JSON object I am receiving from facebook, converted to a string. I assume this is what they want me to use when they say "Payload" is that correct?
It is a string that begins with {"entry":[ and ends with "object":"page"}
I feel like I've tried everything and have hit a brick wall so hoping someone can help me. Web API is a bit off - even grabbing the X-Hub-Signature was a challenge as you can't just use Request.Header["X-Hub-Signature"]; I am almost wondering if I should switch back to pure MVC.
OK so I am answering my own question! The problem with the "Payload" is that you can't simply grab the JSON object. You have to find a way to access the Request object from Web API and then read in the payload like this:
var context = Request.Properties["MS_HttpContext"] as HttpContextWrapper;
using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
payload = reader.ReadToEnd();
}
It looks like binning Web API and just doing this in MVC would be easier as you then just do this:
using (StreamReader reader = new StreamReader(HttpContext.Request.InputStream))
{
PayLoad = reader.ReadToEnd();
}
I'm trying to use this API, which converts files between different formats. As part of the request, it expects the file in Binary format. I'm trying to figure out exactly what that means when it comes to C#. Everything I've read points to using a byte array but that hasn't worked so far.
Essentially, I need to convert a document to binary and then use that raw data and plug it into another part of the system that's responsible for sending the actual POST request.
In an effort to understand the API better, I tested the endpoint and viewed the request payload. Chrome doesn't display the raw data that's sent as part of the File field:
Fiddler does, but it's gibberish (probably because it attempts to interpret the bytes as ASCII):
So I'm a bit confused. For the purposes for that form-data object in the request payload, what do I need to do to the file I have in C#? I tried this (I'm accessing the file from another system using that system's API):
DocumentInfo di = this.BoundEntryInfo as DocumentInfo;
string contentType = "application/msword";
string binaryValue;
using (DocstarReadStream filestream = di.ReadDoc(out contentType)) //open a stream to the word document in the other system
{
using (MemoryStream mstream = new MemoryStream())
{
filestream.CopyTo(mstream);
binaryValue = string.Join("", mstream.ToArray());
}
}
The resulting binaryValue string has a value like this:
807534200608000330223164210108901003250019082916711111011610111011695841211121011159346120109108321624240160020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018014820311019448166924714925015145183859823216217042213962150458223372412328625314619918825419019...
However, using this as the value of the File field in the POST request payload results in a Bad Request error (it says "conversion error" so I'm assuming the data is formatted wrong somehow).
Instead of converting the byte array to a string and sending that as the body, you should instead write the bytes to the request stream being sent through your HttpClient of choice. The content-type encoding is expecting you to send across the raw binary data as the payload, and has no idea what to do with the string interpretation.
This is why the data in fiddler looks like gibberish. It is, as you suspected, a text representation of binary data.
First time posting! I've been breaking my head on this particular case. I've got a Web application that needs to upload a file towards a web-api and receive an SVG file (in a string) back.
The web-app uploads the file as follows:
using (var client = new WebClient())
{
var response = client.UploadFile(apiUrl, FileIGotEarlierInMyCode);
ViewBag.MessageTest = response.ToString();
}
Above works, but then we get to the API Part:
How do I access the uploaded file? Pseudocode:
public string Post([FromBody]File f)
{
File uploadedFile = f;
String svgString = ConvertDataToSVG(uploadedFile);
return s;
}
In other words: How do I upload/send an XML-file to my Web-api, use/manipulate it there and send other data back?
Thanks in advance!
Nick
PS: I tried this answer:
Accessing the exact data sent using WebClient.UploadData on the server
But my code did not compile on Request.InputStream.
The reason Request.InputStream didn't work for you is that the Request property can refer to different types of Request objects, depending on what kind of ASP.NET solution you are developing. There is:
HttpRequest, as available in Web Forms,
HttpRequestBase, as available in MVC Controllers
HttpRequestMessage, as available in Web API Controllers.
You are using Web API, so HttpRequestMessage it is. Here is how you read the raw request bytes using this class:
var data = Request.Content.ReadAsByteArrayAsync().Result;
I have created a simple REST based WCF service which runs on BasicHttpBinding. In one of my webmethod, I am returning a Stream which points to a JSON response.
The Method looks like :
[OperationContract]
[FaultContract(typeof(ApplicationFault))]
[WebInvoke(Method = "POST", UriTemplate = "GetActiveCalls/{nurseid}")]
Stream GetActiveCalls(string nurseid);
From the body of the GetActiveCalls, I am creating an object of MemoryStream and returning the same as response. The code looks like
// Serialize the results as JSON
string jsonResult = new JavaScriptSerializer().Serialize(baseResponses);
// ContentType json
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache");
var bytes = Encoding.UTF8.GetBytes(jsonResult);
//Parse to memorystream
var ms = new MemoryStream(bytes);
ms.Seek(0, SeekOrigin.Begin);
ms.SetLength(bytes.LongLength);
return ms;
When trying this from client, I get result like
{"LastEvents":[{"FormatValues":"Klic 2 3 4","Icon":null,"Color":"Red","Acknowledged":false,"EventID":28566}],"Message":"","Status":true}
But sometimes after invoking the same method for multiple times, I start getting the response as :
{"LastEvents":[{"FormatValues":"Klic 2 3 4","Icon":null,"Color":"Red","Acknowledged":false,"EventID":28566}],"Message":"","Statu{"LastEv
You can see after "Statu on the JSON response, the stream gets reset and starts getting data from the beginning.
It looks strange to me.
*From server side, when I put breakpoint, it seems the MemoryStream has correct response.
Putting aside the question of using a memory stream or not, I encountered a similar issue just recently, where the memory stream response appeared corrupted, seemingly randomly. The solution to this problem was to remove the tracing sections from web.config, which I had turned on in dev mode. This may or may not be your issue, but it might be worth having a look at. Seems as though this problem is still present in .NET 4.5 as well.
I am accessing an API that returns a favicon for a specified domain (http://getfavicon.appspot.com/). I have a long list of domains that I want to get Icons for and don't want to make the call to the web service every time, so I figured I would get the response and store the image either on the file system or in a DB Blob.
However. I don't know how to get something meaningful from the response stream that comes back from the service.
byte[] buf = new byte[8192];
var request = (HttpWebRequest)WebRequest.Create("http://getfavicon.appspot.com/http://stackoverflow.com");
var response = (HttpWebResponse)request.GetResponse();
var resStream = response.GetResponseStream();
I've got as far as here to get a response back, but how would I can I treat this as something I can save to a SQL DB or out to the filesystem?
Am I missing something simple?
Thanks
If you use the System.Net.WebClient class, you can do this a little easier.
This will download the URL and save it to a local file:
var client = new System.Net.WebClient();
client.DownloadFile(
// Url to download
#"http://getfavicon.appspot.com/http://stackoverflow.com",
// Filename of where to save the downloaded content
"stackoverflow.com.ico");
If you want a byte[] instead, use the DownloadData method.