How do you set the Content-Type header for an HttpClient request?

后端 未结 14 2422
暗喜
暗喜 2020-11-22 03:57

I\'m trying to set the Content-Type header of an HttpClient object as required by an API I am calling.

I tried setting the Content-Ty

14条回答
  •  独厮守ぢ
    2020-11-22 04:24

    var content = new JsonContent();
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("charset", "utf-8"));
    content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("IEEE754Compatible", "true"));
    

    It's all what you need.

    With using Newtonsoft.Json, if you need a content as json string.

    public class JsonContent : HttpContent
       {
        private readonly MemoryStream _stream = new MemoryStream();
        ~JsonContent()
        {
            _stream.Dispose();
        }
    
        public JsonContent(object value)
        {
            Headers.ContentType = new MediaTypeHeaderValue("application/json");
            using (var contexStream = new MemoryStream())
            using (var jw = new JsonTextWriter(new StreamWriter(contexStream)) { Formatting = Formatting.Indented })
            {
                var serializer = new JsonSerializer();
                serializer.Serialize(jw, value);
                jw.Flush();
                contexStream.Position = 0;
                contexStream.WriteTo(_stream);
            }
            _stream.Position = 0;
    
        }
    
        private JsonContent(string content)
        {
            Headers.ContentType = new MediaTypeHeaderValue("application/json");
            using (var contexStream = new MemoryStream())
            using (var sw = new StreamWriter(contexStream))
            {
                sw.Write(content);
                sw.Flush();
                contexStream.Position = 0;
                contexStream.WriteTo(_stream);
            }
            _stream.Position = 0;
        }
    
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            return _stream.CopyToAsync(stream);
        }
    
        protected override bool TryComputeLength(out long length)
        {
            length = _stream.Length;
            return true;
        }
    
        public static HttpContent FromFile(string filepath)
        {
            var content = File.ReadAllText(filepath);
            return new JsonContent(content);
        }
        public string ToJsonString()
        {
            return Encoding.ASCII.GetString(_stream.GetBuffer(), 0, _stream.GetBuffer().Length).Trim();
        }
    }
    

提交回复
热议问题