You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Web API如何通过代码发送带JSON请求体的HTTP POST请求

Great to hear your HttpClient implementation is working! Let's walk through the other options you mentioned (WebRequest and WebClient) and clarify how to properly format the JSON request body for each. I'll also share a small improvement to your existing HttpClient code to follow best practices with async/await.


Your HttpClient Code (Improved)

First, your current code uses .Result which can lead to deadlocks in some contexts. Here's the async/await version—this is the recommended approach for modern C#:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        await RunPostAsync();
    }

    private static async Task RunPostAsync()
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        var inputs = new Inputs
        {
            Password = "pw",
            AppVersion = "apv",
            AppComments = "apc",
            UserName = "user",
            AppKey = "apk"
        };

        var jsonContent = JsonConvert.SerializeObject(inputs);
        // Explicitly set UTF-8 encoding and Content-Type header
        var content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");

        try
        {
            var response = await client.PostAsync("https://webapi.com/baseurl/login", content);
            response.EnsureSuccessStatusCode();
            
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine("Response: " + responseBody);
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }

    public class Inputs
    {
        // Changed fields to properties (standard C# practice)
        public string Password { get; set; }
        public string AppVersion { get; set; }
        public string AppComments { get; set; }
        public string UserName { get; set; }
        public string AppKey { get; set; }
    }
}

Using WebRequest (Legacy Low-Level Approach)

WebRequest is an older, more verbose API. Here's how to send your POST request with it:

using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;

class Program
{
    static void Main(string[] args)
    {
        var inputs = new Inputs
        {
            Password = "pw",
            AppVersion = "apv",
            AppComments = "apc",
            UserName = "user",
            AppKey = "apk"
        };
        string json = JsonConvert.SerializeObject(inputs);
        byte[] data = System.Text.Encoding.UTF8.GetBytes(json);

        var request = (HttpWebRequest)WebRequest.Create("https://webapi.com/baseurl/login");
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = data.Length;

        // Write JSON data to the request stream
        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        try
        {
            using (var response = (HttpWebResponse)request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                string responseBody = reader.ReadToEnd();
                Console.WriteLine("Response: " + responseBody);
            }
        }
        catch (WebException ex)
        {
            if (ex.Response is HttpWebResponse errorResponse)
            {
                Console.WriteLine($"Error Status Code: {errorResponse.StatusCode}");
                using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                {
                    string errorBody = reader.ReadToEnd();
                    Console.WriteLine($"Error Body: {errorBody}");
                }
            }
            else
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }

    public class Inputs
    {
        public string Password { get; set; }
        public string AppVersion { get; set; }
        public string AppComments { get; set; }
        public string UserName { get; set; }
        public string AppKey { get; set; }
    }
}

Using WebClient (Simpler Legacy Wrapper)

WebClient is a simpler wrapper around WebRequest, but still considered legacy. Here's the implementation:

using System;
using System.Net;
using Newtonsoft.Json;

class Program
{
    static void Main(string[] args)
    {
        var inputs = new Inputs
        {
            Password = "pw",
            AppVersion = "apv",
            AppComments = "apc",
            UserName = "user",
            AppKey = "apk"
        };
        string json = JsonConvert.SerializeObject(inputs);

        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            try
            {
                string responseBody = client.UploadString("https://webapi.com/baseurl/login", "POST", json);
                Console.WriteLine("Response: " + responseBody);
            }
            catch (WebException ex)
            {
                if (ex.Response is HttpWebResponse errorResponse)
                {
                    Console.WriteLine($"Error Status Code: {errorResponse.StatusCode}");
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        string errorBody = reader.ReadToEnd();
                        Console.WriteLine($"Error Body: {errorBody}");
                    }
                }
                else
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }

    public class Inputs
    {
        public string Password { get; set; }
        public string AppVersion { get; set; }
        public string AppComments { get; set; }
        public string UserName { get; set; }
        public string AppKey { get; set; }
    }
}

Key Notes on Request Body Formatting

  • Serialize to JSON: Use a library like Newtonsoft.Json (Json.NET) or System.Text.Json (built into .NET Core/.NET 5+) to convert your C# object to a valid JSON string. This handles escaping special characters and proper syntax automatically.
  • Set Content-Type Header: Always set the Content-Type header to application/json—this tells the server how to parse the incoming request body.
  • UTF-8 Encoding: Use UTF-8 when converting JSON to bytes or creating request content to support all Unicode characters correctly.

Recommendation

HttpClient is the preferred approach for modern C# applications (since .NET 4.5). It's async-first, supports connection pooling, and has a more intuitive API. WebRequest and WebClient are legacy APIs and should be avoided in new projects.

内容的提问来源于stack exchange,提问作者CraigJSte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:17:53