c# - HTTP POST 多部分表单数据
问题描述
我正在开发 Xamarin.Forms 中的应用程序。我想将发布请求发送到带有表单数据的 API。在下面的代码中,它返回成功消息,但数据并未发布在那里。
public class Post {
public string ConnectionId { get; set; }
public string HolderFirstName { get; set; }
}
public async void SendProof(object sender, EventArgs e) {
try {
Uri URL = new Uri(string.Format("http://11.222.333.44:4000/api/v1/Proof/SendProofNameRequest"));
HttpClient _client = new HttpClient();
var post = new Post {ConnectionId = "9c12dba2-6cb9-4382-8c96-f1708a7e8816", HolderFirstName = "Carl Dreyer"};
var content = JsonConvert.SerializeObject(post);
var response = await _client.PostAsync(URL, new StringContent(content, Encoding.UTF8, "multipart/form-data"));
if (response.IsSuccessStatusCode) {
await DialogService.AlertAsync("Credential Proof Sent Successfully!");}
}
catch(Exception error) {
await DialogService.AlertAsync(error.Message); }
}
绑定触发此功能的按钮。
public ICommand SendProofCommand => new Command(() => SendProof(default, default));
解决方案
public async Task SendProof()
{
try {
HttpClient client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri("http://11.222.333.44:4000/");
var postData = new List<KeyValuePair<string, string>>();
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("ConnectionId", "9c12dba2-6cb9-4382-8c96-f1708a7e8816"));
nvc.Add(new KeyValuePair<string, string>("HolderFirstName", "Bergman"));
var req = new HttpRequestMessage(HttpMethod.Post, "http://11.222.333.44:4000/" + "api/v1/Proof/SendProofNameRequest") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
await DialogService.AlertAsync("Proof Sent Successfully!");
}
else
{
await DialogService.AlertAsync("Unsuccessfull!");
}
}
catch(Exception error) {
await DialogService.AlertAsync(error.Message);
}
}
推荐阅读
- reactjs - 使用状态挂钩将道具向下传递给孩子
- wagtail-streamfield - 最新的 Wagtail 无法编辑现有的流场
- angular - 错误类型错误:a.getCountryCodeOrDefault 不是函数
- javascript - Jquery 切换不隐藏/显示特定元素
- git - 如何在 git 中检查裸仓库的状态
- sourceforge-appscript - 如何缩短下面的代码?谢谢
- python - Celery Crontab 在不挑选任务
- java - 为什么我的进度条渲染不正确?
- c# - ASP.NET Core Identity,如何在不同的数据库中创建用户
- spring-boot - 保存实体需要很长时间才能保存到数据库中,我们如何加快速度?