main
wanggaofeng 1 year ago
parent fb558a85a2
commit 831c769c37

@ -15,31 +15,63 @@ namespace HttpClientStudy.UnitTest
_logger = outputHelper;
}
#region Get请求中使用请求体强烈不推荐这种方法
/// <summary>
/// Get请求中使用请求体
/// 注意:服务器要设置(配置KestrelServerOptions AllowSynchronousIO值为true)
/// </summary>
/// <returns></returns>
[Fact]
public async Task GetWithBodyTestAsync()
public async Task GetWithBody_Test()
{
HttpClient httpClient = new HttpClient();
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("param1", "value1"),
new KeyValuePair<string, string>("param2", "value2")
};
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post,"http://localhost:5189/api/AdvancedGet/GetWithBody");
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get,"http://localhost:5189/api/AdvancedGet/GetWithBody");
requestMessage.Content = new FormUrlEncodedContent(formData);
var response = await httpClient.SendAsync(requestMessage);
response.EnsureSuccessStatusCode();
var responseText = await response.Content.ReadAsStringAsync();
_logger.WriteLine(responseText);
}
/// <summary>
/// Post模型绑定对比
/// </summary>
/// <returns></returns>
[Fact]
public async Task PostDemo_Test()
{
HttpClient httpClient = new HttpClient();
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("param1", "value1"),
new KeyValuePair<string, string>("param2", "value2")
};
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5189/api/AdvancedGet/PostDemo");
requestMessage.Content = new FormUrlEncodedContent(formData);
var response = await httpClient.SendAsync(requestMessage);
response.EnsureSuccessStatusCode();
var responseText = await response.Content.ReadAsStringAsync();
_logger.WriteLine(responseText);
}
#endregion
}
}

@ -25,24 +25,37 @@ namespace HttpClientStudy.WebApp.Controllers
/// <summary>
/// 带请求体数据的Get请求
/// (asp.net 3开始默认不允许Get有Body)
/// 注意:不能直接使用模型绑定接收数据,而应以流的方式读取请求体中的数据
/// </summary>
/// <returns></returns>
[HttpGet]
[HttpPost]
public async Task<IActionResult> GetWithBodyAsync()
{
var requestBody = "";
//以流方式读取请求体中的数据
if (Request.ContentLength>0)
{
using (var reader = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true))
{
var body = await reader.ReadToEndAsync();
requestBody = await reader.ReadToEndAsync();
// 现在你有了请求体,可以按照你的需求处理它
}
}
var result = BaseResultUtil.Success(requestBody);
return Ok(result);
}
var reslut = BaseResultUtil.Success("操作成功");
return Ok(reslut);
/// <summary>
/// Post测试方法
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult PostDemo()
{
var result = BaseResultUtil.Success("操作成功");
return Ok(result);
}
}
}

Loading…
Cancel
Save