How do I get access to the underlying response stream from a WebOperationContext?
Change the return type of the method to Stream.
The code I use for returning an html/text stream is:
public Stream GetHTML()
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
writer.Write("HTML STRING");
conn.Close();
writer.Flush();
stream.Position = 0;
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
return stream;
}
Obviously you'll have a different content type, and I don't think you'll have to use UTF8 encoding.
Related
I have a task which I need to upload a pdf converted to base64 string to Http post. I tried it using refit before but I failed to upload it. Now, I am trying a difference approach.
I used the web request POST method, First I converted the PDF to base64 but on the part that I call the stream.write method, I'm having an error since the file is already converted to base64 string and the stream.write paramater is byte array.
Also, how can I add these to the body using web request?
"mime": "application/pdf",
"data": "base64-data="
string pdfBase64;
const string pdfFileName = "file.pdf";
using (var pdfStream = await FileSystem.OpenAppPackageFileAsync(pdfFileName))
{
using (var pdfReader = new StreamReader(pdfStream))
{
var fileContents = await pdfReader.ReadToEndAsync();
pdfBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileContents));
}
}
WebRequest request = WebRequest.Create("https://goodmorning-axa-dev.azure-api.net/upload");
request.Method = "POST";
request.ContentLength = pdfBase64.Length;
request.ContentType = "application/json";
request.Headers.Add("x-axa-api-key", apiKey);
Stream stream = request.GetRequestStream();
stream.Write(pdfBase64, 0, pdfBase64.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
Toast.MakeText(this, sr.ReadToEnd(), ToastLength.Short).Show();
sr.Close();
stream.Close();
How to read the video file sent from the postman in body binary...
Content-Type : video/mp4
Content-Range: bytes 0-5119999/33230845
Content-Length: 5120000
IFormFile file;
using (var sr = new BufferedStream(Request.Body))
{
var byteArray = await sr.ReadAllBytes();
var stream = new MemoryStream(byteArray);
file = new FormFile(stream, 0, byteArray.Length, "testName", "testFileName");
string path = $"C:\\Projects\\vid{uploadRequest.BlockId}.mp4";
using FileStream str = new FileStream(path, FileMode.Create);
str.Position = 0;
await stream.CopyToAsync(str);
}
public static async Task<byte[]> ReadAllBytes(this Stream instream)
{
if (instream is MemoryStream)
return ((MemoryStream)instream).ToArray();
await using MemoryStream memoryStream = new MemoryStream();
await instream.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
When I save this file into C Disk and open it, says that: item is unplayable...
How do I post GZip data using RestSharp. I have the following code but it isn't working as I would expect:
var restRequest = new RestRequest(url, Method.POST)
{
Timeout = Constants.DefaultTimeoutMilliseconds
};
var dataStream = new MemoryStream();
using (var zipStream = new GZipStream(dataStream, CompressionMode.Compress))
{
using (var writer = new StreamWriter(zipStream))
{
writer.Write(new DotNetXmlSerializer().Serialize(content));
}
}
var compressedBytes = dataStream.ToArray();
restRequest.AddParameter("application/x-gzip", compressedBytes, ParameterType.RequestBody);
return _restClient.Execute<TResponseData>(restRequest);
When I run this and check the wireshark trace, the compressedBytes variable is posted as
'System.Byte[]' - as if ToString() has been called on it despite the parameter being a system.object.
If I pass the compressed byte array through as a string using both Convert.ToBase64String() and Encoding.Utf8.GetString() then I am unable to decompress the GZip at the server. I simply get 'System.IO.InvalidDataException: The magic number in GZip header is not correct. Make sure you are passing in a GZip'.
Is there any way of posting Gzipped data using RestSharp?
Make sure you've updated to the latest version of RestSharp (like 104.4.0) as this was a bug in a previous version.
I think this was fixed in 104.2 where the PUT or POST of binary data ended up with the System.Byte[] being represented as the string.
Update your NuGet reference and try it again. Good luck!
var body = "some string";
var dataStream = new MemoryStream();
byte[] dataToCompress = Encoding.UTF8.GetBytes(body);
using (var memoryStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(memoryStream, CompressionLevel.Optimal))
{
gzipStream.Write(dataToCompress, 0, dataToCompress.Length);
}
dataStream = memoryStream;
}
var client = new RestClient("url");
var request = new RestRequest("", Method.POST);
var compressedBytes = dataStream.ToArray();
request.AddHeader("Content-Encoding", "gzip");
request.AddParameter("application/x-gzip", compressedBytes, ParameterType.RequestBody);
//client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
IRestResponse response = await client.ExecuteAsync(request);
Console.WriteLine(response.Content);
Am using below url to upload a file to dropbox using oauth and am getting an error
{"error": "Call requires one of the following methods: PUT, POST, got GET!"}
am passing httpmethod as PUT but still asking the error.
Signature am using to upload is
https://api-content.dropbox.com/1/files_put/dropbox/test?oauth_consumer_key=twcek2m7cxtantc&oauth_signature_method=PLAINTEXT&oauth_token=918v4lxg2w23car&oauth_version=1.0&oauth_signature=fbs34nykryouuj1%26rbbprgh95tjzf22
using this am getting the error
{"error": "Call requires one of the following methods: PUT, POST, got GET!"}
please tell me anyone what to do for resolve this error.
public FileSystemInfo UploadFile(string root, string path, string file)
{
var uri = new Uri(new Uri(DropboxRestApi.ApiContentServer),
String.Format("files_put/{0}/{1}",
root, UpperCaseUrlEncode(path)));
var oauth = new OAuth();
//var requestUri = oauth.DownloadSignRequest(uri, _consumerKey, _consumerSecret, "POST", _accessToken);
var requestUri = oauth.SignRequest(uri, _consumerKey, _consumerSecret, _accessToken, "PUT");
var request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = WebRequestMethods.Http.Post;
request.KeepAlive = true;
byte[] buffer;
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
int length = (int) fileStream.Length;
buffer = new byte[length];
fileStream.Read(buffer, 0, length);
}
request.ContentLength = buffer.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
}
// request.Method = "POST";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var json = reader.ReadToEnd();
return ParseJson<FileSystemInfo>(json);
}
I made a mistaken in saving path of the file where i want to upload it.
Give the same file name for save in path.
that's all.
How can I convert Windows.Storage.Streams.IRandomAccessStream to System.IO.Stream?
I'm using a C# library which accepts System.IO.Stream as input, but when I open files in Metro I get Windows.Storage.Streams.IRandomAccessStream.
The easiest way is to call AsStream.
You can convert Windows.Storage.Streams.IRandomAccessStream to a byte[] and then convert byte[] to a System.IO.Stream.
Byte[] from IRandomAccessStream
var file = await new FileOpenPicker().PickSingleFileAsync();
var fStream = await file.OpenAsync(FileAccessMode.Read);
var reader = new DataReader(fStream.GetInputStreamAt(0));
var bytes = new byte[fStream.Size];
await reader.LoadAsync((uint)fStream.Size);
reader.ReadBytes(bytes);
Stream from Byte[]
var stream = new MemoryStream(bytes);