关于c#:如何为HttpClient PostAsync第二个参数设置HttpContent?

How do I set up HttpContent for my HttpClient PostAsync second parameter?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}

PostAsync采用另一个需要为HttpContent的参数。

如何设置HttpContent? 没有任何适用于Windows Phone 8的文档。

如果我执行GetAsync,效果很好! 但它必须是POST,其内容为key =" bla",something =" yay"

//编辑

非常感谢您的回答...效果很好,但是在这里仍然不确定:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    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;
    }

我假设数据" test = something"将在api方面作为发布数据" test"获得,显然不是。 另一方面,我可能需要通过发布数据来发布整个对象/数组,因此我认为json将是最好的选择。 关于如何获取帖子数据的任何想法?

也许像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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


在有关Cant查找如何使用HttpContent的一些答案以及本博客文章中,都对此进行了回答。

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


为了增加Preston的答案,以下是标准库中提供的HttpContent派生类的完整列表:

Credit: 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),然后您可以执行以下操作:

1
2
3
4
5
var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
    Title ="New Article Title",
    Body ="New Article Body"
});