【问题标题】:Nancy : parsing "multipart/form-data" requestsNancy:解析​​“multipart/form-data”请求
【发布时间】:2017-01-13 03:01:14
【问题描述】:

我有一个 RestSharp 客户端和 Nancy Self Host Server。 我想要的是

从客户端发送多部分表单数据并轻松解析该数据 来自服务器:

从 RestSharp 客户端发送二进制文件和 Json 数据作为多部分表单数据 并能够从 Nancy Server 获取二进制文件和 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);

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

【问题讨论】:

    标签: rest restsharp nancy


    【解决方案1】:

    对于多部分数据,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/

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多