Upload File Through C# Using JSON Request and Restsharp

Upload file through c# using JSON request and RestSharp

This was a fight... In the end I discovered two different ways of solving this problem. The irony of it, as so many of coding problems, was that all i had to do was setting the right parameters in first place...Just one missing parameter cost me more than 4 hours..

Both detailed below :

1 - Use RestSharp (the total field shouldn't be there, and the ispaperduplicate field was missing)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;

namespace RonRestClient
{

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

string path = @"C:\filename2.pdf";
//localhost settings
string requestHost = @"http://localhost:3000/receipts";
string tagnr = "p94tt7w";
string machinenr = "2803433";
string safe_token = "123";

// Do it with RestSharp

templateRequest req = new templateRequest();
req.receipt = new templateRequest.Receipt(tagnr);
req.machine = new templateRequest.Machine(machinenr, safe_token);

var request = new RestRequest("/receipts", Method.POST);
request.AddParameter("receipt[tag_number]", tagnr);
request.AddParameter("receipt[ispaperduplicate]", 0);
request.AddParameter("machine[serial_number]", machinenr);
request.AddParameter("machine[safe_token]", safe_token);
request.AddFile("receipt[receipt_file]", File.ReadAllBytes(path), Path.GetFileName(path), "application/octet-stream");

// Add HTTP Headers
request.AddHeader("Content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
//set request Body
//request.AddBody(req);

// execute the request
//calling server with restClient
RestClient restClient = new RestClient("http://localhost:3000");
restClient.ExecuteAsync(request, (response) =>
{

if (response.StatusCode == HttpStatusCode.OK)
{
//upload successfull
MessageBox.Show("Upload completed succesfully...\n" + response.Content);
}
else
{
//error ocured during upload
MessageBox.Show(response.StatusCode + "\n" + response.StatusDescription);
}
});

}

}

}

2 - Use FileStream with HttpWebRequest (thank you Clivant)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;

namespace RonRestClient
{

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

string path = @"C:\Projectos\My Training Samples\Adobe Sample\RBO1574.pdf";
//localhost settings
string requestHost = @"http://localhost:3000/receipts";
string tagnr = "p94tt7w";
string machinenr = "2803433";
string safe_token = "123";

FileStream fs1 = File.OpenRead(path);
long filesize = fs1.Length;
fs1.Close();

// Create a http request to the server endpoint that will pick up the
// file and file description.
HttpWebRequest requestToServerEndpoint =
(HttpWebRequest)WebRequest.Create(requestHost);

string boundaryString = "FFF3F395A90B452BB8BEDC878DDBD152";
string fileUrl = path;

// Set the http request header \\
requestToServerEndpoint.Method = WebRequestMethods.Http.Post;
requestToServerEndpoint.ContentType = "multipart/form-data; boundary=" + boundaryString;
requestToServerEndpoint.KeepAlive = true;
requestToServerEndpoint.Credentials = System.Net.CredentialCache.DefaultCredentials;
requestToServerEndpoint.Accept = "application/json";

// Use a MemoryStream to form the post data request,
// so that we can get the content-length attribute.
MemoryStream postDataStream = new MemoryStream();
StreamWriter postDataWriter = new StreamWriter(postDataStream);

// Include value from the tag_number text area in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"receipt[tag_number]",
tagnr);

// Include ispaperduplicate text area in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"receipt[ispaperduplicate]",
0);

// Include value from the machine number in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"machine[serial_number]",
machinenr);

// Include value from the machine token in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"machine[safe_token]",
safe_token);

// Include the file in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n"
+ "Content-Length: \"{2}\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n\r\n",
"receipt[receipt_file]",
Path.GetFileName(fileUrl),
filesize);

postDataWriter.Flush();

// Read the file
FileStream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
postDataStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();

postDataWriter.Write("\r\n--" + boundaryString + "--\r\n");
postDataWriter.Flush();

// Set the http request body content length
requestToServerEndpoint.ContentLength = postDataStream.Length;

// Dump the post data from the memory stream to the request stream
Stream s = requestToServerEndpoint.GetRequestStream();

postDataStream.WriteTo(s);

postDataStream.Close();

}

}

}

Sending Rest request with file(s) and JSON (Restsharp) on Framework and Standard

This isn't directly an answer but merely the solution I came up with to work around the problem.

I switched to Flurl.Http which the latest version is compatible with both Standard and Framework. This is how I rewrote my SendEmail function,

public void SendEmail(MicroserviceMailMessage email)
{
var url = _azureEndpoint;
var transformedEmail = TransformEmail(email);

var content = new CapturedMultipartContent();
content.AddJson("email", transformedEmail);

foreach (var attachment in email.Attachments)
{
var inline = attachment.ContentDisposition.Inline ? "inline." : "";
content.AddFile($"attachments.{inline}{attachment.Name}", attachment.ContentStream, attachment.Name);
}

url.PostAsync(content).Wait();
}

It posts everything I need successfully, the files, and the JSON.

RestSharp JSON Parameter Posting

You don't have to serialize the body yourself. Just do

request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new { A = "foo", B = "bar" }); // Anonymous type object is converted to Json body

If you just want POST params instead (which would still map to your model and is a lot more efficient since there's no serialization to JSON) do this:

request.AddParameter("A", "foo");
request.AddParameter("B", "bar");

How to send json Data using RestSharp POST Method in c#

in your web api you need to handle the binding json data. WebApi does it by itself normally.
And also you dont have to add header or any parameter with "application/json".
If you could just simply use AddJsonBody(object obj) method RestSharp will automatically set the header.

Or another way to do that is:

    Random r = new Random((int)DateTime.Now.Ticks);
var x = r.Next(100000, 999999);
string s = x.ToString("000000");
string UniqueFileName = "S" + s + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
request.Resource = "api/BFormat/AddNewBFormat";
request.Method = Method.POST;
request.RequestFormat = DataFormat.Json;
var body = new
{
UploadFileVM = new
{
BordereauxId = "",
BFormatId = "",
FileName = UniqueFileName,
Filesize = 0,
Path = @"c:\sdakdldas\"
}
};
request.AddBody(body); //enter code herE
var queryResult = client.Execute<ResponseData<Guid>>(request).Data;
try
{
Assert.IsTrue(queryResult.ReturnData != null);

}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}

And don't serialize the data by urself. RestSharp will take care of serializing.



Related Topics



Leave a reply



Submit