休息 – 南希:解析“multipart / form-data”请求

我有一个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/]我尝试发送包含二进制文件和json格式的一些元数据的“multipart / form-data”请求:

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/],Itry获取文件和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/

点赞