mJa*_*Jay 6 c# http-headers flurl
我正在使用flurl提交HTTP请求,这非常有用.现在我需要将一些请求的" Content-Type"标题更改为"application/json; odata = verbose"
public async Task<Job> AddJob()
{
var flurlClient = GetBaseUrlForGetOperations("Jobs").WithHeader("Content-Type", "application/json;odata=verbose");
return await flurlClient.PostJsonAsync(new
{
//Some parameters here which are not the problem since tested with Postman
}).ReceiveJson<Job>();
}
private IFlurlClient GetBaseUrlForOperations(string resource)
{
var url = _azureApiUrl
.AppendPathSegment("api")
.AppendPathSegment(resource)
.WithOAuthBearerToken(AzureAuthentication.AccessToken)
.WithHeader("x-ms-version", "2.11")
.WithHeader("Accept", "application/json");
return url;
}
Run Code Online (Sandbox Code Playgroud)
你可以看到我试图在上面添加标题(.WithHeader("Content-Type", "application/json;odata=verbose"))
不幸的是,这给了我以下错误:
"InvalidOperationException:Misused header name.确保请求头与HttpRequestMessage一起使用,响应头与HttpResponseMessage一起使用,内容头与HttpContent对象一起使用."
我也尝试了flurl的"ConfigureHttpClient"方法,但无法找到设置内容类型标头的方式/位置.
这个答案已经过时了。升级到最新版本(2.0或更高版本),问题消除了。
事实证明,真正的问题与System.Net.HttpAPI 如何验证标头有关。它在请求级标头和内容级标头之间进行了区分,由于原始HTTP没有这种区分,所以我总是发现这有点奇怪(也许在多部分场景中除外)。Flurl WithHeader将标头添加到HttpRequestMessage对象,但未通过验证Content-Type,它希望将标头添加到HttpContent对象。
这些API确实允许您跳过验证,尽管Flurl不会直接公开它,但是您可以很容易地掌握要件,而不会破坏流畅的链条:
return await GetBaseUrlForGetOperations("Jobs")
.ConfigureHttpClient(c => c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;odata=verbose"))
.PostJsonAsync(new { ... })
.ReceiveJson<Job>();
Run Code Online (Sandbox Code Playgroud)
这可能是最好的方法,可以做您需要的并且仍然利用Flurl的优点,即不必直接处理序列化,HttpContent对象等。
我强烈考虑基于此问题更改Flurl的AddHeader(s)实现TryAddWithoutValidation。
我发现的评论和另一篇文章(当我再次找到它时将添加参考)已经为我指明了正确的方向。我的问题的解决方案如下所示:
var jobInJson = JsonConvert.SerializeObject(job);
var json = new StringContent(jobInJson, Encoding.UTF8);
json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=verbose");
var flurClient = GetBaseUrlForOperations("Jobs");
return await flurClient.PostAsync(json).ReceiveJson<Job>();
Run Code Online (Sandbox Code Playgroud)
编辑:找到相关的SO问题:Azure编码作业通过REST失败