![](/img/trans.png)
[英]Send values from Windows Forms Application to Asp.Net Core Api
[英]Calling .NET core REST api from windows forms to send data including IFormFile
我有一個使用此模型的.NET核心Web Api:
public class UserForRegisterDto
{
[Required]
public string UserName { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string PhoneNumber { get; set; }
[Required]
public string MobilePhone { get; set; }
[Required]
public IFormFile Photo { get; set; }
}
另一方面,我有一個使用.NET 4的Windows窗體應用程序,我嘗試使用此類和代碼將數據發送到api:
public class UserForRegisterDto
{
public string UserName { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string PhoneNumber { get; set; }
public string MobilePhone { get; set; }
public byte[] Photo { get; set; }
}
發送此數據的代碼是:
List<UserForRegisterDto> registrationList = Mapper.Map<List<UserForRegisterDto>>(usersList);
AuthenticatedHttpClientHandler clientHandler = new AuthenticatedHttpClientHandler(user.Id, Uow, _refreshTokenService);
clientHandler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(clientHandler);
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["appUrl"].ToString());
StringContent content = new StringContent(JsonConvert.SerializeObject(registrationList), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"api/users/{user.Id}/users/PostGasStationUsers/{ConfigurationManager.AppSettings["appId"].ToString()}", content);
我需要使用其他數據類型而不是可以映射到IFormFile數據的字節數組以及如何做到這一點。
使用MultipartFormDataContent
傳輸二進制數據
var content = new MultipartFormDataContent();
for (int i = 0; i < registrationList.Count; i++)
{
UserForRegisterDto registration = registrationList[i];
content.Add(new StringContent(registration.LastName), $"model[{i}].LastName");
content.Add(new StringContent(registration.MobilePhone), $"model[{i}].MobilePhone");
content.Add(new StringContent(registration.Name), $"model[{i}].Name");
content.Add(new StringContent(registration.Password), $"model[{i}].Password");
content.Add(new StringContent(registration.PhoneNumber), $"model[{i}].PhoneNumber");
content.Add(new StringContent(registration.UserName), $"model[{i}].UserName");
content.Add(new ByteArrayContent(registration.Photo), $"model[{i}].Photo", "photo.jpeg");
}
HttpResponseMessage response = await client.PostAsync($"api/users/{user.Id}/users/PostGasStationUsers/{ConfigurationManager.AppSettings["appId"].ToString()}", content);
如果動作參數名稱為model
[HttpPost]
public IActionResult PostGasStationUsers(List<UserForRegisterDto> model)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.