1
public string Post(T obj)
    {
        HttpRequestMessage request = new HttpRequestMessage();
        MediaTypeFormatter[] formatter = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };
        var content = request.CreateContent<T>(obj, MediaTypeHeaderValue.Parse("application/json"), formatter, new FormatterSelector());
        HttpResponseMessage response = client.PostAsync(this.url, content).Result;
        return response.Content.ToString();
    }

this is my method Post, that i use in my HTTPClient, but there is one problem - CreateContent and FormatterSelector - is classes from old references. How to rewrite this code to latest references:

using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using Newtonsoft.Json;

I understand in what problem. This methods is extension methods! So they are unavailable to me.

4

1 に答える 1

2

You can try this piece of code:

public async Task<string> Post<T>(T obj)
    {
        MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
        HttpContent content = new ObjectContent<T>(obj, jsonFormatter);

        var response = await client.PostAsync(this.Url, content);
        return response.Content.ToString();
    }
于 2013-12-09T13:30:12.400 に答える