I have a RestSharp Client and Nancy Self Host Server. What I want is
To send multipart form data from client and parse that data easily from server :
Send binary file and Json data As Multipart Form Data from RestSharp client and able to get binary file and Json object from Nancy Server
At Client using Restsharp : [ http://restsharp.org/ ] I try to send "multipart/form-data" requests which contains a binary file plus some meta data in json format:
var client = new RestClient();
...
IRestRequest restRequest = new RestRequest("AcmeUrl", Method.POST);
restRequest.AlwaysMultipartFormData = true;
restRequest.RequestFormat = DataFormat.Json;
// I just add File To Request
restRequest.AddFile("AudioData", File.ReadAllBytes("filePath"), "AudioData");
// Then Add Json Object
MyObject myObject = new MyObject();
myObject.Attribute ="SomeAttribute";
....
restRequest.AddBody(myObject);
client.Execute<MyResponse>(request);
At Server using Nancy[ http://nancyfx.org/ ], Itry to get File and Json Object [Meta Data ]
// Try To Get File : It Works
var file = Request.Files.FirstOrDefault();
// Try To Get Sended Meta Data Object : Not Works.
// Can Not Get MyObject Data
MyObject myObject = this.Bind<MyObject>();
For multipart data, Nancy's code is a bit more complex. Try something like this:
Post["/"] = parameters =>
{
try
{
var contentTypeRegex = new Regex("^multipart/form-data;\\s*boundary=(.*)$", RegexOptions.IgnoreCase);
System.IO.Stream bodyStream = null;
if (contentTypeRegex.IsMatch(this.Request.Headers.ContentType))
{
var boundary = contentTypeRegex.Match(this.Request.Headers.ContentType).Groups[1].Value;
var multipart = new HttpMultipart(this.Request.Body, boundary);
bodyStream = multipart.GetBoundaries().First(b => b.ContentType.Equals("application/json")).Value;
}
else
{
// Regular model binding goes here.
bodyStream = this.Request.Body;
}
var jsonBody = new System.IO.StreamReader(bodyStream).ReadToEnd();
Console.WriteLine("Got request!");
Console.WriteLine("Body: {0}", jsonBody);
this.Request.Files.ToList().ForEach(f => Console.WriteLine("File: {0} {1}", f.Name, f.ContentType));
return HttpStatusCode.OK;
}
catch (Exception ex)
{
Console.WriteLine("Error!!!!!! {0}", ex.Message);
return HttpStatusCode.InternalServerError;
}
};
Have a look at: http://www.applandeo.com/en/net-and-nancy-parsing-multipartform-data-requests/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With