Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nancy : parsing "multipart/form-data" requests

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>();
like image 619
Hippias Minor Avatar asked Oct 19 '22 15:10

Hippias Minor


1 Answers

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/

like image 123
Starnuto di topo Avatar answered Oct 21 '22 20:10

Starnuto di topo