如何更改FLURL客户端的HTTP请求内容类型? [英] How to change the HTTP Request Content Type for FLURL Client?

查看:707
本文介绍了如何更改FLURL客户端的HTTP请求内容类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flurl提交HTTP请求,这非常有用。现在我需要将某些请求的 Content-Type标题更改为application / json; odata = verbose

I am using flurl to submit HTTP request and this is very useful. Now I need to change the "Content-Type" header for some of the requests to "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;
    }

您可以看到我是如何尝试添加上面的标题( .WithHeader(Content-Type,application / json; odata = verbose)

You can see how I tried to add the header above (.WithHeader("Content-Type", "application/json;odata=verbose"))

不幸的是这给了我以下错误:

Unfortunately this gives me following error:


InvalidOperationException:Misused header name。确保请求
标头与HttpRequestMessage一起使用,响应标头与
一起使用HttpResponseMessage和带有HttpContent对象的内容标题。

"InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."

我还尝试了flurl的ConfigureHttpClient方法,但无法找到如何/在何处设置内容类型标题。

I also tried flurl's "ConfigureHttpClient" method but could not find how/where to set the content type header.

推荐答案

我发现的评论和另一篇文章(将在我再次找到时添加参考)指出了我正确的方向。
我的问题的解决方案如下:

The comments and another post I found (will add reference when I find it again) have pointed me to the right direction. The solution for my problem looks like:

        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>();

编辑:找到相关的SO问题: Azure编码作业通过REST失败

Found the related SO question: Azure encoding job via REST Fails

这篇关于如何更改FLURL客户端的HTTP请求内容类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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