【发布时间】:2018-08-08 18:11:40
【问题描述】:
我正在使用带有 Refit 的 multipart。我尝试为我的服务上传个人资料图片 postman 生成的代码是这样的
var client = new RestClient("http://api.example.com/api/users/1");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "xxx");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"_method\"\r\n\r\nput\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"profile_picture\"; filename=\"ic_default_avatar.png\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
然后我像这样构造 Refit 方法
[Multipart]
[Post("/users/{id}")]
IObservable<BaseResponse<User>> UpdateProfilePicture(int id,[AliasAs("profile_picture")] byte[] profilePicture,[AliasAs("_method")]string method="put");
如果我使用byte[] 或ByteArrayPart 会抛出异常
{System.Net.Http.HttpRequestException: 发送时出错 请求---> System.Net.WebException:获取响应时出错 流(分块 Read2):ReceiveFailure ---> System.Exception:在 System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x00031] in :0 在 System.Net.WebConnection.Read(System.Net.HttpWebRequest 请求, System.Byte[] 缓冲区,System.Int32 偏移量,System.Int32 大小) [0x000d2] 在 :0 处 System.Net.WebConnectionStream.ReadAll() [0x0010e] 在 :0 在 System.Net.HttpWebResponse.ReadAll() [0x00011] 在 :0 在 System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult 结果)[0x001d6] in :0 at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData 数据) [0x0013e] in :0 在 System.Net.WebConnection.ReadDone(System.IAsyncResult 结果) [0x0024d] 在 :0 处 System.Net.Sockets.SocketAsyncResult+c.b__27_0 (System.Object 状态)[0x00000] 中 :0 在 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00015] 在 :0 处 System.Threading.ThreadPoolWorkQueue.Dispatch() [0x00074] in :0 在 ObjCRuntime.Runtime.ThreadPoolDispatcher (System.Func`1[TResult] 回调)[0x00006] 在 :0 处 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() [0x00009] 在 :0 处 System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x00031] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.12.0.4/src/Xamarin.iOS/mcs/class/System/System.Net/WebConnection.cs:439
。如果我使用Stream 或StreamPart 它也会抛出异常说流已关闭。
【问题讨论】: