无法使用c#HttpClient发送Content-Type标头 [英] Can't send Content-Type header with c# HttpClient

查看:723
本文介绍了无法使用c#HttpClient发送Content-Type标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在"multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w"的c#HttpClient请求中设置Content-Type标头.

I'm trying to set a Content-Type header in a c# HttpClient request of "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w".

到目前为止,我已经尝试使用TryAddWithoutValidation,它不会引发任何异常/错误,但是当我在提琴手中观看请求时,它是否未添加?参见下面的代码.

So far I've tried using TryAddWithoutValidation which does not throw any exception/error but when I watch the request in fiddler its just not added? See code below.

client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w");
response = client.PostAsync("https://example.com", byteContent).Result;

我还尝试将要发送的字节数组转换为字符串并使用StringContent,但这会引发异常,说明"multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w"无效.

I've also tried converting the byte array I'm trying to send to a string and using StringContent but this throws an exception saying "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w" is invalid.

StringContent testStringcontent = new StringContent(Encoding.Default.GetString(allContentBytes), Encoding.UTF8, "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w");
response = client.PostAsync("https://example.com", testStringcontent).Result;

我已经尝试了所有类似的问题建议,但看不到要发送的头文件或抛出任何异常.我应该放弃此方法,使用被告知更灵活的Web客户端吗?

I've tried all the similar questions suggestions and can't see to get any to send the header or not throw some sort of exception. Should I abandon this and use web client which I'm told is more flexible?

推荐答案

与之配合使用

ByteArrayContent byteContent = new ByteArrayContent(allContentBytes);
byteContent.Headers.Remove("Content-Type");
byteContent.Headers.Add("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w");

这篇关于无法使用c#HttpClient发送Content-Type标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆