首页 > 解决方案 > 如何使用 fetch() javascript 方法将数据发布到 .NET Core Web API

问题描述

我正在尝试将数据从 React 前端发布到 .NET Core Web API 方法。我正在使用fetch()javascript 方法发布。当我在 .NET 代码中设置断点来分析 viewModel 的值时,它的所有成员都为空。

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

我试过[FromBody]在参数前面添加属性。

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);
        });
    });

}

联系人控制器.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);
    }

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;}

}

我期望数据填充视图模型属性,但它们都是空的。Firefox 的开发工具显示请求在正文中传递 JSON 参数。

标签: javascriptc#restasp.net-corefetch

解决方案


修改您的代码:

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/jsonas content-type 发布 json 字符串。在服务器端接收值[FromBody]

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

   ....
}

推荐阅读