记C# HttpClient Post 使用

本文记录C# 使用HttpClient Post上传参数、文件的方法。

服务端传入参数是[FromForm]格式

WebAPI:

1
2
3
4
5
6
7
[HttpPost]
public IActionResult setlampSample([FromForm] string parStr,
[FromForm] int parA,
[FromForm] bool parB)
{
return Ok(new { status = 0, msg = "OK" });
}

HttpClient:

1
2
3
4
5
6
7
8
9
10
11
static void Test1(string url)
{
HttpClient httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"parStr", "aabbcc"},
{"parA", "111"},
{"parB", "True"},
});
var response = httpClient.PostAsync(url, content).Result;
}

服务端传入参数是Object

WebAPI:

1
2
3
4
5
[HttpPost]
public IActionResult setlampSampleB(demoModel obj)
{
return Ok(new { status = 0, msg = "OK" });
}

HttpClient:

方法一:

1
2
3
4
5
6
7
static void Test2(string url)
{
HttpClient httpClient = new HttpClient();
StringContent content = new StringContent(JsonSerializer.Serialize(new demoModel() { parA = 123, parB = "456", parC = true }));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = httpClient.PostAsync(url, content).Result;
}

方法二:

1
2
3
4
5
static void Test3(string url)
{
HttpClient httpClient = new HttpClient();
var response = httpClient.PostAsJsonAsync(url, new demoModel() { parA = 789, parB = "321", parC = false }).Result;
}

HttpClient文件上传

WebAPI

1
2
3
4
5
6
7
8
[HttpPost]
[RequestSizeLimit(524288000)]
public async Task<IActionResult> Upload(IFormFile file)
{
var files = Request.Form.Files;
return Ok(new { status = 0, msg = "OK" });

}

HttpClient:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
static async Task Test4(string url,string filePath)
{
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(300);// 设置超时
using (var content = new MultipartFormDataContent())
{
var fs = File.OpenRead(filePath);
var streamContent = new StreamContent(fs);
streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");


content.Add(streamContent, "file", Path.GetFileName(filePath));// 添加文件到表单

HttpResponseMessage response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();// 确保请求成功

string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}

Demo

源码下载