c# - 如何使用asp net core http客户端将文件和文本数据发布到web api?
问题描述
我有一个看起来像这样的模型,我有文本数据和四张照片要发送:
public class Layout1
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Titulo { get; set; }
[Required]
[StringLength(50)]
public string FotoN1 { get; set; }
[Required]
public IFormFile FotoN1File { get; set; }
[Required]
[StringLength(50)]
public string FotoN2 { get; set; }
[Required]
public IFormFile FotoN2File { get; set; }
[Required]
[StringLength(50)]
public string FotoN3 { get; set; }
[Required]
public IFormFile FotoN3File { get; set; }
[Required]
[StringLength(50)]
public string FotoN4 { get; set; }
[Required]
public IFormFile FotoN4File { get; set; }
[Required]
[StringLength(50)]
public string Botao { get; set; }
public string ClienteId { get; set; }
}
我想将它发布在我的 api 上,为了接收这个模型,我有以下代码:
[HttpPost("AddLayout")]
public async Task<IActionResult> AddLayout([FromForm] Layout1 layout)
{
if (ModelState.IsValid)
{
if (layout == null)
{
throw new NullReferenceException("Layout model não existe");
}
layout.FotoN1 = await SaveImage(layout.FotoN1File);
layout.FotoN2 = await SaveImage(layout.FotoN2File);
layout.FotoN3 = await SaveImage(layout.FotoN3File);
layout.FotoN4 = await SaveImage(layout.FotoN4File);
_context.Layout1.Add(layout);
await _context.SaveChangesAsync();
return Ok(new Response
{
Message = "Layout criado!",
IsSucess = true
});
}
return BadRequest(new Response
{
Message = "Erro na criação do layout",
IsSucess = false,
});
}
当我使用 Postman 时它可以工作,但我不知道如何使用 http 客户端发送它。 向邮递员提出要求。
如何像在 Postman 中使用我的 http 客户端一样发出请求?现在我有以下代码,但它给出了一个 400 错误请求并说所有属性都是空的,我想这是因为我发送了一个 json 但是我的表单是多部分表单数据。
[HttpPost]
public async Task<IActionResult> AddLayout1(IFormCollection dados, IFormFile FotoN1, IFormFile FotoN2, IFormFile FotoN3, IFormFile FotoN4)
{
var id = HttpContext.Session.GetString("Id");
if (ModelState.IsValid) {
Layout1 layout = new Layout1();
layout.Titulo = dados["Titulo"];
layout.Botao = dados["Botao"];
layout.FotoN1 = FotoN1.FileName;
layout.FotoN1File = FotoN1;
layout.FotoN2 = FotoN2.FileName;
layout.FotoN2File = FotoN2;
layout.FotoN3 = FotoN3.FileName;
layout.FotoN3File = FotoN3;
layout.FotoN4 = FotoN4.FileName;
layout.FotoN4File = FotoN4;
layout.ClienteId = id;
var data = new StringContent(
JsonConvert.SerializeObject(layout, Formatting.Indented),
Encoding.UTF8,
"application/json"
);
var authToken = HttpContext.Session.GetString("Token");
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
var response = await _client.PostAsync(_APIserver + "/api/cliente/AddLayout", data);
var responsebody = await response.Content.ReadAsStringAsync();
var responseObject = JsonConvert.DeserializeObject<Response>(responsebody);
if (responseObject.IsSucess && responseObject != null)
{
return RedirectToAction("Index", "Home", new { Type = "success", Message = responseObject.Message });
}
else
{
return RedirectToAction("Index", "Home", new { Type = "danger", Message = responseObject.Message });
}
}
return View();
}
谢谢!!
解决方案
如何使用asp net core http客户端将文件和文本数据发布到web api
public async Task<IActionResult> AddLayout([FromForm] Layout1 layout)
如果您想向AddLayout
端点发出带有表单数据的 HTTP 请求,请参阅以下代码片段。
//...
var formContent = new MultipartFormDataContent();
formContent.Add(new StringContent("blabla"), "Titulo");
//...
formContent.Add(new StringContent(Path.GetFileName(FotoN1.FileName)), "FotoN1");
formContent.Add(new StreamContent(FotoN1.OpenReadStream()), "FotoN1File", Path.GetFileName(FotoN1.FileName));
//...
//for other properties, such as FotoN2, FotoN2File etc
//...
var response = await _client.PostAsync(_APIserver + "/api/cliente/AddLayout", formContent);
if (response.IsSuccessStatusCode)
{
//...
推荐阅读
- php - 带有 isset() 的 for 循环!= null - 为什么?
- java - Spring Boot、Gradle 和 Visual Studio Code - Gradle bootRun 任务无法正常工作
- java - 如何在 Java 中处理大型数据库表而不会遇到性能问题
- php - Yii2:如何转换 JSON PHP 数组的数据类型值?
- oracle - JPA Criteria API - 使用 ORACLE 将日期添加到 DATE
- javascript - mongoose.connect(), first argument should be String, received undefined
- sql - 更改跟踪以显示值之前和之后
- ethereum - 在 Remix IDE 中部署合约后,Solidity 函数返回 0x00000 的管理器地址
- php - restrict users directly redirecting to another page by editing url
- node.js - mongoose 中的模块导出