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

前端 未结 2 1901
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 17:07
public static async Task GetData(string url, string data)
{
    UriBuilder fullUri = new UriBuilder(url);

    if (!string.IsNullOrEmpty(data))
                


        
相关标签:
2条回答
  • 2020-11-29 17:23

    This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post.

    In summary, you can't directly set up an instance of HttpContent because it is an abstract class. You need to use one the classes derived from it depending on your need. Most likely StringContent, which lets you set the string value of the response, the encoding, and the media type in the constructor. See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx

    0 讨论(0)
  • 2020-11-29 17:45

    To add to Preston's answer, here's the complete list of the HttpContent derived classes available in the standard library:

    Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

    There's also a supposed ObjectContent but I was unable to find it in ASP.NET Core.

    Of course, you could skip the whole HttpContent thing all together with Microsoft.AspNet.WebApi.Client extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:

    var response = await client.PostAsJsonAsync("AddNewArticle", new Article
    {
        Title = "New Article Title",
        Body = "New Article Body"
    });
    
    0 讨论(0)
提交回复
热议问题