如何使用没有字符集的DataContractJsonSerializer在C#中发送JSON
发布时间:2020-12-16 19:32:21 所属栏目:百科 来源:网络整理
导读:我使用DataContractJsonSerializer和StringContent将 JSON发送到Web服务: DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Employee));MemoryStream ms = new MemoryStream();serializer.WriteObject(ms,employee);ms.Posi
我使用DataContractJsonSerializer和StringContent将
JSON发送到Web服务:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Employee)); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms,employee); ms.Position = 0; StreamReader sr = new StreamReader(ms); StringContent jsonContent = new StringContent(sr.ReadToEnd(),System.Text.Encoding.UTF8,"application/json"); // later I do HttpClient.PostAsync(uri,jsonContent) 这会导致此Content-Type标头: Content-Type: application/json; charset=utf-8 是否有可能离开字符集,只是有以下标题? Content-Type: application/json 我没有在StringContent上看到这样做的重载.
我一直有同样的问题,无论我设置什么字符集,它总是声称我试图使用“不支持的媒体类型”.我发现使用这种方法将字符集留空(正如Slack试图做的那样)解决了我的问题.诀窍是指定内容类型 – 这是绝对必要的 – 稍后(我刚才在下一行做了):
StringContent content = new StringContent("Whatever=something"); content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json"); (请原谅内容的非真实JSON格式,这不是我的例子.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |