Where is the PostAsJsonAsync method in ASP.NET Core?

后端 未结 14 1820
再見小時候
再見小時候 2020-12-29 00:51

I was looking for the PostAsJsonAsync() extension method in ASP.NET Core. Based on this article, it\'s available in the Microsoft.AspNet.WebApi.Client

14条回答
  •  梦毁少年i
    2020-12-29 01:36

    To follow on from the answers above, I have a small addition that was required for me to get it to work.

    Previously I was using a .NET Core 2.1 web app using the PostAsJsonAsync() method, and when I upgraded to .NET Core 3.1 it no longer worked.

    I could not get the above answers to work, and it turned out to be because the text to be posted had to be surrounded by quotes, and any quotes within it had to be escaped. I made the following extension method, which solved my problem:

    public static async Task PostJsonAsync(this HttpClient client, string uri, string json)
    {
        //For some reason, not doing this will cause it to fail:
        json = $"\"{json.Replace("\"", "\\\"")}\"";
    
        return await client.PostAsync(uri, new StringContent(json, Encoding.UTF8, "application/json"));
    }
    

    Note that I am using the System.Text.Json.JsonSerializer as opposed to the Newtonsoft version.

提交回复
热议问题