2016-02-16 64 views
3

我有一個RestSharp客戶端和Nancy Self Host Server。 我要的是Nancy:解析​​「multipart/form-data」請求

從客戶端輕鬆 從服務器發送多形式的數據和分析數據:

從RestSharp客戶 和能夠得到的二進制發送二進制文件和JSON數據作爲多部分表單數據文件和JSON對象從南希服務器

在客戶端使用 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); 

在使用南希[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>(); 

回答

1

對於多數據,南希的代碼是有點複雜。 嘗試是這樣的:

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/