首页 > 解决方案 > .NET Core Web API 参数绑定问题 [FromForm] 和 [FromBody]

问题描述

public async Task<IActionResult> Register([FromForm] RegisterViewModel model)
{

}

这是一个 Web 控制器操作,我从另一个简单的控制器向它传递了一个模型:

HttpResponseMessage response = await client.PostAsJsonAsync("api/Account/Register", model);

问题是模型(RegisterViewModel)包含一个IFormFile类型字段并发送它,我必须使用[FromForm],但它仅在数据直接从表单提交到 api 时才有效,但我将表单提交到简单的控制器并将其提交到 api使用 HttpClient 如果我使用[FromBody]它接受所有其他字段但它不会接受IFormFile字段

    public class RegisterViewModel
    {
        [Required]
        [Display(Name = "Email")]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required(ErrorMessage = "Enter First Name:")]
        [StringLength(maximumLength: 30, MinimumLength = 3)]
        [MaxLength(30)]
        [Display(Name = "First Name")]
        public string firstName { get; set; }

        [Required(ErrorMessage = "Enter Last Name:")]
        [StringLength(maximumLength: 30, MinimumLength = 3)]
        [MaxLength(30)]
        [Display(Name = "Last Name")]
        public string lastName { get; set; }

        [Required(ErrorMessage = "Please Select Profile Picture")]
        public IFormFile profilePicture { get; set; }
        public string profilePictureName { get; set; }

        [StringLength(200)]
        [MaxLength(200)]
        [Display(Name = "Add Facebook Link To Your Profile")]
        [DataType(DataType.Url)]
        public string facebookLink { get; set; }

        [StringLength(200)]
        [MaxLength(200)]
        [Display(Name = "Add Instagram Link To Your Profile")]
        [DataType(DataType.Url)]
        public string instagramLink { get; set; }

        [StringLength(200)]
        [MaxLength(200)]
        [Display(Name = "Add Twitter Link To Your Profile")]
        [DataType(DataType.Url)]
        public string twitterLink { get; set; }

        [Required(ErrorMessage = "Enter Date Of Birth:")]
        [DataType(DataType.Date)]
        public DateTime DOB { get; set; }

        [Required]
        [Display(Name = "Registration No")]
        public string season { get; set; }
        [Required]
        public string department { get; set; }
        [Required]
        public string roll { get; set; }

        public IEnumerable<SelectListItem> seasons { get; set; }
        public IEnumerable<SelectListItem> departments { get; set; }
    }

标签: asp.net-core.net-coreasp.net-core-mvcasp.net-core-webapi

解决方案


推荐阅读