我有一个 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”请求,其中包含一个二进制文件以及一些 json 格式的元数据:
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/ ]、尝试获取File和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/
关于rest - 南希 : parsing "multipart/form-data" requests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35426826/