【问题标题】:Uploading images with swagger大摇大摆地上传图片
【发布时间】:2022-09-28 00:09:56
【问题描述】:

我的数据库中有一个用餐实体。我想用图像发布它。 控制器:

[HttpPost]
        public async Task<ActionResult> AddMeal([FromForm]CreateMealDto newMeal, [FromForm]IFormFile image)
        {
            if(image == null || image.Length == 0)
            {
                newMeal.mealPhotoPath = \"\";
            }
            else
            {
                var path = Path.Combine(webHostEnvironment.WebRootPath, \"UploadedImages\", image.FileName);

                using (FileStream stream = new FileStream(path, FileMode.Create))
                {
                    await image.CopyToAsync(stream);
                    stream.Close();
                }
                newMeal.mealPhotoPath = path;
            }
            var meal = await mealsService.AddMealAsync(newMeal);
            return Created($\"/meals.{meal.id}\", new Response<MealDto>(meal));
        }

餐点:

public record CreateMealDto
    {
        public string name { get; init; }
        public int weightInGrams { get; init; }
        public decimal calories { get; init; }
        public decimal protein { get; init; }
        public decimal carbohydrates { get; init; }
        public decimal fat { get; init; }
        public string ingredients { get; init; }
        public string recipe { get; init; }
        public string mealPhotoPath { get; set; }
    }

餐饮实体:

[Table(\"Meals\")]
public record Meal : AuditableEntity
{
    [Key]
    public Guid id { get; init; }
    [Required]
    [MaxLength(50)]
    public string name { get; init; }
    [Required]
    public int weightInGrams { get; init; }
    [Required]
    public decimal calories { get; init; }
    [Required]
    public decimal protein { get; init; }
    [Required]
    public decimal carbohydrates { get; init; }
    [Required]
    public decimal fat { get; init; }
    [Required]
    [MaxLength(500)]
    public string ingredients { get; init; }
    [Required]
    [MaxLength(1000)]
    public string recipe { get; init; }
    public string mealPhotoPath { get; init; }
    public Meal() { }
    public Meal(string _name, int _weightInGrams, decimal _calories, decimal _protein,
        decimal _carbohydrates, decimal _fat, string _ingredients, string _recipe, string _mealPhotoPath) 
    {
        id = Guid.NewGuid();
        (name, weightInGrams, calories, protein, carbohydrates, fat, ingredients, recipe, mealPhotoPath) = (_name,
            _weightInGrams, _calories, _protein, _carbohydrates, _fat, _ingredients, _recipe, _mealPhotoPath);
    }
}

通过邮递员上传文件没有问题,但是说到招摇我希望它看起来像这样 how it should look like

但它看起来像这样 how it look like

为什么会这样?

    标签: .net api web swagger


    【解决方案1】:

    似乎当我从 IFormFile 中删除 [FromForm] 属性时,它开始使用 swagger 但停止使用邮递员。我还不知道是否有人有想法请告诉我。

    【讨论】:

      猜你喜欢
      • 2020-07-12
      • 2019-05-11
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 2018-11-29
      相关资源
      最近更新 更多