【问题标题】:Passing data FromBody and FromForm in the same endpoint在同一端点中传递数据 FromBody 和 FromForm
【发布时间】:2021-12-20 01:41:24
【问题描述】:

我正在.Net Core Web API 中创建一个商店项目。 我有一个负责创建新产品的端点。 在正文中,我传递了一个标准 DTO 模型,其中包括“名称、价格”等。现在我想将图像字段添加到产品中。这些图像将保存在数据库中的服务器和 URL 上。 我知道图像应该通过 Form 传递,但是可以通过 Form 和 Body 在一个端点传递数据吗?但是,我应该为此操作创建一个单独的端点吗?

编辑: 现在我有:

        [HttpPost]
        public ActionResult Create([FromBody] CreatePerfumeDto dto)
        {

如果我从 [FromBody] 更改为 [FromForm] 会好吗?

        [HttpPost]
        public ActionResult Create([FromForm] CreatePerfumeDto dto)
        {

【问题讨论】:

  • 表单数据在请求正文中传递。可以通过“多部分表单数据”请求同时传递图像和信息。
  • 我的回答对你有用吗?

标签: .net asp.net-core .net-core asp.net-web-api


【解决方案1】:

FromForm 和 FromBody,只能选择其中之一使用。

如果你使用`[FromBody]`,你的文件需要转换成base64格式,然后你才能上传。

如果你使用`[FromForm]`,你可以使用`IFormFile`。

示例代码

public class CreatePerfumeDto
{
    public string Name { get; set; }
    public string Price { get; set; }
    public IFormFile formfile { get; set; }
    public string fileName { get; set; }
}

[HttpPost("upload")]
public ActionResult CreateForm([FromForm] CreatePerfumeDto dto)
{
    var file = dto.formfile;   
    return Ok(file.FileName);
}

【讨论】:

    猜你喜欢
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多