简体   繁体   English

将内容类型标头添加到 httpclient GET 请求

[英]Add content-type header to httpclient GET request

I am trying to add Content-Type header to HttpClient GET request, here my code:我正在尝试将Content-Type标头添加到 HttpClient GET请求,这里是我的代码:

HttpClient client=new ....
bool added = client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
var response = await client.GetAsync(...

but the added variable is false, ie it failed to add the header.但是added变量是假的,即添加标题失败。

How can I add this header?如何添加此标题?

NOTE:笔记:

This post deals with POST request, I asked about GET 这篇文章处理POST请求,我询问了GET

If you look at the Http/1.1 specification :如果您查看Http/1.1 规范

A sender that generates a message containing a payload body SHOULD generate a Content-Type header field in that message unless the intended media type of the enclosed representation is unknown to the sender.生成包含有效负载主体的消息的发送者应该在该消息中生成 Content-Type 头字段,除非发送者不知道所包含的表示的预期媒体类型。 If a Content-Type header field is not present, the recipient MAY either assume a media type of "application/octet-stream" ([RFC2046], Section 4.5.1) or examine the data to determine its type.如果 Content-Type 头域不存在,接收者可以假设媒体类型为“application/octet-stream”([RFC2046],第 4.5.1 节)或检查数据以确定其类型。

Check also the MDN on get requests还要检查 关于获取请求MDN

The HTTP GET method requests a representation of the specified resource. HTTP GET 方法请求指定资源的表示。 Requests using GET should only retrieve data.使用 GET 的请求应该只检索数据。

Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined.在 GET 请求中发送 body/payload 可能会导致一些现有的实现拒绝请求——虽然规范没有禁止,但语义是未定义的。 It is better to just avoid sending payloads in GET requests.最好避免在 GET 请求中发送有效负载。

Effectively, that means that wether you send or not the header, it's going to be ignored and/or rejected.实际上,这意味着无论您是否发送标头,都将被忽略和/或拒绝。

When setting the content type, it's better to set it from the content itself: How do you set the Content-Type header for an HttpClient request?设置内容类型时,最好从内容本身设置How do you set the Content-Type header for HttpClient request?

Im currently working on a project, where I call an api using a POST request.我目前正在做一个项目,在那里我使用 POST 请求调用 api。 This might help in your case.这可能对您的情况有所帮助。 Its how its done in an official Microsoft Documentation.它是如何在官方 Microsoft 文档中完成的。

using (var content = new ByteArrayContent(byteData))
{
// This example uses the "application/octet-stream" content type.
// The other content types you can use are "application/json"
// and "multipart/form-data".
content.Headers.ContentType = new mediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uriBase, content);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM