首页 > 解决方案 > 如何使用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();
    }

谢谢!!

标签: c#asp.net-coreasp.net-web-api

解决方案


如何使用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)
{
    //...

推荐阅读