How to change the HTTP Request Content Type for FLURL Client?

前端 未结 5 1864
小鲜肉
小鲜肉 2021-01-18 10:39

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 \"appl

5条回答
  •  一向
    一向 (楼主)
    2021-01-18 11:29

    This answer is outdated. Upgrade to latest version (2.0 or above) and the problem goes away.

    It turns out the real issue has to do with how the System.Net.Http APIs validate headers. It makes a distinction between request-level headers and content-level headers, which I've always found a bit odd since raw HTTP makes no such distinction (except perhaps in multipart scenarios). Flurl's WithHeader adds headers to the HttpRequestMessage object but is failing validation for Content-Type, which it expects to be added to the HttpContent object.

    Those APIs do allow you to skip validation, and although Flurl doesn't expose it directly, you can get under the hood pretty easily, without breaking the fluent chain:

    return await GetBaseUrlForGetOperations("Jobs")
        .ConfigureHttpClient(c => c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;odata=verbose"))
        .PostJsonAsync(new { ... })
        .ReceiveJson();
    

    This is probably the best way to do what you need and still take advantage of Flurl's goodness, i.e. not have to directly deal with serialization, HttpContent objects, etc.

    I'm strongly considering changing Flurl's AddHeader(s) implementations to use TryAddWithoutValidation based on this issue.

提交回复
热议问题