Can RestSharp send binary data without using a multipart content type?

后端 未结 6 2224
闹比i
闹比i 2020-12-14 12:48

I have been using AddParameter to include XML bodies in my HTTP requests:

request.AddParameter(contentType, body, ParameterType.RequestBody);
         


        
6条回答
  •  一整个雨季
    2020-12-14 13:20

    I ran into the same issue. I had to upload exactly one file and use a specific content type for communicating with an REST Interface. You could modify Http.RequestBody to byte[] (and all dependencies on that), but i think its easier this way:

    I modified RestSharp, so that it only use Multipart Encoding when number of Files > 1 or number of Files = 1 and there is also body or other post data set.

    You have to modify Http.cs on Line 288 from

    if(HasFiles)
    

    to

    if(Files.Count > 1 || (Files.Count == 1 && (HasBody || Parameters.Any())))
    

    For Http.Sync.cs modify PreparePostData from

    private void PreparePostData(HttpWebRequest webRequest)
    {
        if (HasFiles)
        {
            webRequest.ContentType = GetMultipartFormContentType();
            using (var requestStream = webRequest.GetRequestStream())
            {
                WriteMultipartFormData(requestStream);
            }
        }
    
        PreparePostBody(webRequest);
    }
    

    to

    private void PreparePostData(HttpWebRequest webRequest)
    {
        // Multiple Files or 1 file and body and / or parameters
        if (Files.Count > 1 || (Files.Count == 1 && (HasBody || Parameters.Any())))
        {
            webRequest.ContentType = GetMultipartFormContentType();
            using (var requestStream = webRequest.GetRequestStream())
            {
                WriteMultipartFormData(requestStream);
            }
        }
        else if (Files.Count == 1)
        {
            using (var requestStream = webRequest.GetRequestStream())
            {
                Files.Single().Writer(requestStream);
            }
        }
    
        PreparePostBody(webRequest);
    }
    

    If you use the async version, you have to modify the code similar to the above in Http.Async.cs.

    Now u can use RestSharp like this

    IRestRequest request = new RestRequest("urlpath", Method.PUT);
    request.AddHeader("Content-Type", "application/zip");
    request.AddFile("Testfile", "C:\\File.zip");
    
    Client.Execute(request);
    

    AddFile also provides an overload for setting direct byte[] data instead of a path. Hope that helps.

提交回复
热议问题