如何使用asp.net核心中的Fetch api将数据传递给控制器

Ale*_*der 13 c# asp.net-core-mvc asp.net-core

我在我的客户端js脚本中使用这样的fetch发布数据

    fetch('/myarea/mycontroller/myaction', {
        method: 'post',
        body: JSON.stringify({ name: namevalue, address: addressvalue })
    })
        .then(function (response) {
            if (response.status !== 200) {
                console.log('fetch returned not ok' + response.status);
            }

            response.json().then(function (data) {
                console.log('fetch returned ok');
                console.log(data);
            });
        })
        .catch(function (err) {
            console.log(`error: ${err}`);
        });
    }, false);
Run Code Online (Sandbox Code Playgroud)

然后在我的控制器上

    [HttpPost]      
    public async Task<IActionResult> MyAction(string name, string address)
    {
        // Error, name and address is null here, shouldn't be!
        // more code here ...
    }
Run Code Online (Sandbox Code Playgroud)

正在调用我的控制器操作,我可以在其中调试,但没有传递数据.这可能有什么问题?谢谢

eri*_*zic 7

控制器操作期待查询参数(/myaction?name=myname&address=myaddress).这是默认值.你把它们送到身体里.

您可以更改javascript以将其作为查询参数发送.(见这里:https://github.com/github/fetch/issues/256)

或者您可以告诉控制器操作从身体获取值:

[HttpPost]      
public async Task<IActionResult> MyAction([FromBody] Person person)
{
    var myName = person.Name;
}

public class Person
{
    public string Name {get; set; }

    public string Address {get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 它现在可以工作了!我只是像这样设置 fetch api headers: 'Content-Type': 'application/json;' (2认同)
  • 无法添加[FromBody],将Content-Type设置为application / json的事件 (2认同)

Kia*_*aha 5

[FromBody] 属性仅在我定义了“application/json”类型的标头后才为我启动:

fetch('api/Profile/Update', {
        method: 'post',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ description: "Some text here" })
    });
Run Code Online (Sandbox Code Playgroud)

这就是控制器动作的样子:

    [HttpPost("[action]")]
    public async Task<IActionResult> Update([FromBody] ProfileUpdateModel profileUpdateModel)
    {
        //Do some stuff here...
        return  RedirectToAction("/", "HomeController");
    }
Run Code Online (Sandbox Code Playgroud)

并且 description 属性现在接收来自请求的值。希望这能让解决这个问题的人最终清楚。