簡體   English   中英

如何使用C#HttpClient正確執行JSON對象的HTTP Post?

[英]how to properly perform HTTP Post of a JSON object using C# HttpClient?

我有一個非常簡單的C#Http客戶端控制台應用程序,它需要對WebAPI v2執行json對象的HTTP POST。 目前,我的應用程序可以使用FormUrlEncodedContent進行POST:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Net.Http.Formatting;


namespace Client1
{
    class Program
    {
        class Product
        {
            public string Name { get; set; }
            public double Price { get; set; }
            public string Category { get; set; }
        }
        static void Main(string[] args)
        {
             RunAsync().Wait();
        }
        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:8888/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var content = new FormUrlEncodedContent(new[] 
                        {
                            new KeyValuePair<string, string>("Category", "value-1"),
                            new KeyValuePair<string, string>("Name", "value-2")                           
                       });

                var result = client.PostAsync("Incident", content).Result;      
                var r = result;     
            }
        }
    }
}

但是,當我嘗試在POST正文中使用JSON時,我收到錯誤415 - 不支持的媒體類型:

class Product
{
    public string Name { get; set; }
    public double Price { get; set; }
    public string Category { get; set; }
}

var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
var  response = await client.PostAsJsonAsync("api/products", gizmo);

執行顯式JSON序列化不會改變我的結果:

string json = JsonConvert.SerializeObject(product);
var  response = await client.PostAsJsonAsync("api/products", json);

處理這個問題的正確方法是什么,並且能夠POST JSON?

當我發布FormUrlEncodedContent時,這是我正在使用的代碼的范圍

        HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            {"grant_type", "password"},
            {"client_id", _clientId},
            {"client_secret", _clientSecret},
            {"username", _userName},
            {"password", _password}
        }
            );

            var message =
                await httpClient.PostAsync(_authorizationUrl, content);

其中_authorizationUrl是一個絕對的url。

我沒有設置任何這些屬性

           client.BaseAddress = new Uri("http://localhost:8888/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

像你一樣。

如果您希望它作為FormUrlEncodedContent發送,則MediaTypeWithQualityHeaderValue(“application / json”)是錯誤的。 這會將請求content-type設置為json。 使用application / x-www-form-urlencoded或者根本不設置MediaTypeWithQualityHeaderValue。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM