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

后端 未结 6 2251
闹比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条回答
  •  Happy的楠姐
    2020-12-14 13:20

    I had the same problem, but I didn't fancy forking the code and I didn't like the alternative suggested by Michael as the documentation says "RequestBody: Used by AddBody() (not recommended to use directly)".

    Instead I replaced the RestClient.HttpFactory with my own:

    RestClient client = GetClient();
    
    var bytes = await GetBytes();
    client.HttpFactory = new FactoryWithContent { GetBytes = () => new Bytes(bytes, "application/zip") };
    
    var request = new RestRequest();
    return await client.ExecutePostTaskAsync(request);
    

    Where Bytes and FactoryWithContent look like:

    public class Bytes
    {
        public Bytes(byte[] value, string type)
        {
            Value = value;
            Type = type;
        }
    
        public byte[] Value { get; private set; }
        public string Type { get; private set; }
    }
    
    public class FactoryWithContent : IHttpFactory
    {
        public IHttp Create()
        {
            var http = new Http();
    
            var getBytes = GetBytes;
            if (getBytes != null)
            {
                var bs = getBytes();
                http.RequestBodyBytes = bs.Value;
                http.RequestContentType = bs.Type;
            }
    
            return http;
        }
    
        public Func GetBytes { get; set; }
    }
    

提交回复
热议问题