C# HttpClient 在字典字符串/对象中使用 FormUrlEncodedContent 对象发布内容

Ale*_*dro 3 c# encoding json http httpclient

我正在尝试将内容发布到我的服务器。这就是我过去一直这样做的方式,直到我不得不使用字符串以外的对象为止。

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authType, tokens);
    var postParams = new Dictionary<string, object>();

    postParams.Add("string", string);
    postParams.Add("int", string);
    postParams.Add("datetime", DateTime);
    postParams.Add("datetime", DateTime);
    postParams.Add("Match", Match);
    postParams.Add("TicketId", token);

    using (var postContent = new FormUrlEncodedContent(postParams.ToDictionary()))
    {
        var myContent = JsonConvert.SerializeObject(postParams);
        var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
        var byteContent = new ByteArrayContent(buffer);
        byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        using (HttpResponseMessage response = await client.PostAsync(@"http://url/api", byteContent))
        {
            response.EnsureSuccessStatusCode(); // Throw if httpcode is an error
            using (HttpContent content = response.Content)
            {
                string result = await content.ReadAsStringAsync();
                var Json = JsonConvert.DeserializeObject<bool>(result);
                return Json;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我的要求。

methode: POST
object: {
    "title":"test-ticket-2",
    "detail": "Description test create ticket in prod",
    "dateStart": "2019-10-06",
    "dateEnd": "2019-10-12",
    "ratio": "2.15",
    "matchResult": "2",
    "matchs": [
            {
                "Teams": "Test-match-1",
                "Proposal": "3x",
                "DateStart": "2019-10-06 18:00",
                "DateEnd": "2019-10-06 20:00",
                "Payout": "0.6"
            }
             ]
Run Code Online (Sandbox Code Playgroud)

我不知道是否以及如何添加字符串以外的对象并发出请求。有任何想法吗?

编辑:Match看起来像这样

public class Match
{
    public int Id { get; set; }
    public string Teams { get; set; }
    public string MatchResults { get; set; }
    public string Proposal { get; set; }
    public string Payout { get; set; }
    public DateTime? DateStart { get; set; }
    public DateTime? DateEnd { get; set; }
    public Uri Ball { get; set; }
    public int TicketId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

我如何添加字符串以外的对象并发出请求。有任何想法吗?

using (HttpClient httpclient = new HttpClient()) 
{
    Models.ApplicationUser applicationUser = new ApplicationUser();
    string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(applicationUser);
    StringContent stringContent = new StringContent(serialized);
    httpclient.PostAsync("url", stringContent);
}
Run Code Online (Sandbox Code Playgroud)

希望你想做这样的事情

  • 我需要字典中的不同对象。解决方案是将两者声明为对象并在必要时删除 FormUrlEncodedContent。由于您的答案涵盖了其中的一部分,因此它被接受为答案。 (2认同)