如何为我的HttpClient PostAsync第二个参数设置HttpContent?

Jim*_*988 237 c# httpcontent dotnet-httpclient

public static async Task<string> GetData(string url, string data)
{
    UriBuilder fullUri = new UriBuilder(url);

    if (!string.IsNullOrEmpty(data))
        fullUri.Query = data;

    HttpClient client = new HttpClient();

    HttpResponseMessage response = await client.PostAsync(new Uri(url), /*expects HttpContent*/);

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();

    return responseBody;
}
Run Code Online (Sandbox Code Playgroud)

PostAsync采取一个需要另一个参数HttpContent.

我该如何设置HttpContent?任何适用于Windows Phone 8的文档都没有.

如果我这样做GetAsync,那就太棒了!但它需要POST的内容为key ="bla",某事="yay"

//编辑

非常感谢答案......这很有效,但这里还有一些不确定的地方:

    public static async Task<string> GetData(string url, string data)
    {
        data = "test=something";

        HttpClient client = new HttpClient();
        StringContent queryString = new StringContent(data);

        HttpResponseMessage response = await client.PostAsync(new Uri(url), queryString );

        //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();

        return responseBody;
    }
Run Code Online (Sandbox Code Playgroud)

我认为数据"test = something"会在api一侧作为后期数据"测试",显然它没有.另一方面,我可能需要通过post数据发布整个对象/数组,所以我认为json最好这样做.有关如何通过数据发布的任何想法?

也许是这样的:

class SomeSubData
{
    public string line1 { get; set; }
    public string line2 { get; set; }
}

class PostData
{
    public string test { get; set; }
    public SomeSubData lines { get; set; }
}

PostData data = new PostData { 
    test = "something",
    lines = new SomeSubData {
        line1 = "a line",
        line2 = "a second line"
    }
}
StringContent queryString = new StringContent(data); // But obviously that won't work
Run Code Online (Sandbox Code Playgroud)

Pre*_*lot 144

这在一些答案中得到了解答无法找到如何使用HttpContent以及此博客文章.

总之,您无法直接设置实例,HttpContent因为它是一个抽象类.您需要根据需要使用从中派生的类.最有可能的是StringContent,它允许您在构造函数中设置响应的字符串值,编码和媒体类型.请参阅:http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx

  • 我会检查一下.我想当我发现它时,我将不得不把它放在每个人都可以看到它的地方!这让我有4天了,试图让一个简单的REST到API. (2认同)
  • 快速回答"我如何发布我的类的JSON reprsentation"是"将对象序列化为JSON,可能与JSON.Net",但这真的属于一个单独的问题. (2认同)

Ser*_*gan 80

要添加到Preston的答案,这里HttpContent是标准库中可用的派生类的完整列表:

图片来源:https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

图片来源:https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

还有一个假设,ObjectContent但我无法找到它ASP.NET Core.

当然,您可以将HttpContent所有内容与Microsoft.AspNet.WebApi.Client扩展一起跳过(您必须进行导入才能使其在ASP.NET Core中正常工作:https://github.com/aspnet/Home/issues/1558)然后你可以做以下事情:

var response = await client.PostAsJsonAsync("AddNewArticle", new Post
{
    Title = "New Article Title",
    Body = "New Article Body"
});
Run Code Online (Sandbox Code Playgroud)

  • 最全面的答案..非常整洁的方式来完成看似复杂的任务。 (2认同)

Md *_*iar 15

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }
Run Code Online (Sandbox Code Playgroud)