问题

我正在尝试从React前端POST数据到.NET Core Web API方法.我正在使用fetch() javascript方法POSTing.当我在.NET代码中设置断点以分析viewModel的值时,其所有成员都为null.

我也尝试传递一个简单的字符串而不是视图模型,但这也是null.

我已经尝试在参数前添加[FromBody]属性.

c# – ContactForm.js

 onSubmit(e) {
    e.preventDefault();

    let data = {
        viewModel: {
            name: this.state.name,
            serviceRequested: this.state.interest,
            email: this.state.email,
            phone: this.state.phone,
            contactPreference: this.state.preference
        }
    };

    fetch('api/Contact/Contact', {
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)      
    })
    .then(response => {
        response.text().then(function (text) {
            alert(text);
        });
    });

}
 

c# – ContactController.cs

 private readonly string successMessage = "success";
private readonly string modelStateMessage = "Invalid input.";

[HttpPost("[action]")]
public ActionResult Contact(ContactFormViewModel viewModel)
    {
        if (ModelState.IsValid)
        {

        }
        else 
        {
            return Content(modelStateMessage);
        }

        return Content(successMessage);
    }
 

c# – ContactFormViewModel.cs

 public class ContactFormViewModel {

    [Required]
    public string Name {get;set;}

    public string ServiceRequested {get; set;}

    [DataType(DataType.EmailAddress)]
    public string Email {get;set;}

    [DataType(DataType.PhoneNumber)]
    public string Phone {get;set;}

    public string ContactPreference {get;set;}

    [StringLength(1000)]
    public string Message {get;set;}

}
 

我期待数据填充视图模型属性,但它们都是null. Firefox的开发工具显示Request在正文中传递JSON参数.

  最佳答案

修改代码:

 let data = {
    viewModel: {
        name: this.state.name,
        serviceRequested: this.state.interest,
        email: this.state.email,
        phone: this.state.phone,
        contactPreference: this.state.preference
    }
};
 

至:

 let data = {                    
    name: this.state.name,
    serviceRequested: this.state.interest,
    email: this.state.email,
    phone: this.state.phone,
    contactPreference: this.state.preference
};
 

并保持客户端代码以application/json作为content-type发布json字符串.使用[FromBody]在服务器端接收值:

 [HttpPost("[action]")]
public ActionResult Contact([FromBody]ContactFormViewModel viewModel)
{

   ....
}
 

  相同标签的其他问题

javascriptc#restasp.net-corefetch