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

北慕城南 提交于 2019-12-01 17:39:31

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

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.

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

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

Biagio Paruolo
public static class Utils
{
    public static IFlurlClient GetBaseUrlForOperations(string resource)
    {
        var _apiUrl = "https://api.mobile.azure.com/v0.1/apps/";

        var url = _apiUrl
            .AppendPathSegment("Red-Space")
            .AppendPathSegment("HD")
            .AppendPathSegment("push")
            .AppendPathSegment("notifications")
            .WithHeader("Accept", "application/json")
            .WithHeader("X-API-Token", "myapitocken");

            return url;
    }

    public static async Task Invia()
    {
        FlurlClient _client;
        PushMessage pushMessage = new PushMessage();
        pushMessage.notification_content = new NotificationContent();

        try
        {
            var flurClient = Utils.GetBaseUrlForOperations("risorsa");
            // News news = (News)contentService.GetById(node.Id);
            //pushMessage.notification_target.type = "";
            pushMessage.notification_content.name = "A2";
            // pushMessage.notification_content.title = node.GetValue("TitoloNews").ToString();
            pushMessage.notification_content.title = "Titolo";
            pushMessage.notification_content.body = "Contenuto";
            var jobInJson = JsonConvert.SerializeObject(pushMessage);
            var json = new StringContent(jobInJson, Encoding.UTF8);
            json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
            dynamic data2 = await flurClient.PostAsync(json).ReceiveJson();
            var expandoDic = (IDictionary<string, object>)data2;
            var name = expandoDic["notification_id"];
            Console.WriteLine(name);
        }
        catch (FlurlHttpTimeoutException ex)
        {
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + " " + ex);
        }
        catch (FlurlHttpException ex)
        {
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + " " + ex);
            if (ex.Call.Response != null)
                Console.WriteLine("Failed with response code " + ex.Call.Response.StatusCode);
            else
                Console.WriteLine("Totally failed before getting a response! " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + " " + ex);
        }
    }
}

public class NotificationTarget
{
    public string type { get; set; }
}

public class CustomData {}

public class NotificationContent
{
    public string name { get; set; }
    public string title { get; set; }
    public string body { get; set; }
    public CustomData custom_data { get; set; }
}

public class PushMessage
{
    public NotificationTarget notification_target { get; set; }
    public NotificationContent notification_content { get; set; }
}

I'm not an OData expert and I don't know what API you're calling (SharePoint?), but based on most examples I've seen, what you typically want to do is ask the server to send verbose OData in the response, rather than declare that you're sending it in the request. In other words, you want to set the ;odata=verbose bit on the Accept header, not Content-Type. application/json should be good enough for Content-Type, and Flurl will set that for you automatically, so just try this change and see if it works:

.WithHeader("Accept", "application/json;odata=verbose");

Am I allowed to post 3 answers to the same question? :)

Upgrade. Flurl.Http 2.0 includes the following enhancements to headers:

  1. WithHeader(s) now uses TryAddWithoutValidation under the hood. With that change alone, the OP's code will work as originally posted.

  2. Headers are now set at the request level, which solves another known issue.

  3. When using SetHeaders with object notation, underscores in property names will be converted to hyphens in the header names, since hyphens in headers are very common, underscores are not, and hyphens are not allowed in C# identifiers.

This will be useful in your case:

.WithHeaders(new {
    x_ms_version = "2.11",
    Accept = "application/json"
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!