How to change the content type of an HTTP request for a FLURL client?

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

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

Unfortunately, this gives me the following error:

"InvalidOperationException: invalid header name. Headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."

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

+4
5

, ( , ), . :

        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 Fails

0

. (2.0 ), .

, , API- System.Net.Http . -, , raw 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>();

, , , , - Flurl, .. , HttpContent ..

Flurl AddHeader(s) TryAddWithoutValidation .

+3

OData, , API (SharePoint?), , , , , OData , , . , ;odata=verbose , Content-Type. application/json Content-Type, Flurl , , :

.WithHeader("Accept", "application/json;odata=verbose");
0
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; }
}
0

3 ?:)

. Flurl.Http 2.0 :

  • WithHeader(s) TryAddWithoutValidation . OP .

  • , .

  • SetHeaders , , - , #.

:

.WithHeaders(new {
    x_ms_version = "2.11",
    Accept = "application/json"
});
0

Source: https://habr.com/ru/post/1679109/


All Articles