南希:正在解析 "multipart/form-data" 个请求

Nancy : parsing "multipart/form-data" requests

我有一个 RestSharp 客户端和 Nancy 自托管服务器。 我要的是

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

在客户端 使用 Restsharp:[http://restsharp.org/] 我尝试发送 "multipart/form-data" 请求,其中包含二进制文件和 [=25] 中的一些元数据=]格式:

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);

在服务器上使用 Nancy[http://nancyfx.org/],尝试获取文件和Json对象[元数据]

// 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>();

对于多部分数据,Nancy 的代码稍微复杂一些。 尝试这样的事情:

 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;
        }
    };

看看: http://www.applandeo.com/en/net-and-nancy-parsing-multipartform-data-requests/