如何使用ASP.NET Core中的Fetch API将数据传递到控制器 [英] How to pass data to controller using Fetch api in asp.net core

查看:452
本文介绍了如何使用ASP.NET Core中的Fetch API将数据传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I post data using fetch like this in my client js scripts

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

然后在我的控制器上

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

我的控制器动作被正确调用,并且我可以在其中进行调试,但是没有数据被传递.这有什么问题吗?谢谢

My controller action is being called correctly, and I am able to debug inside it, but no data being passed. What could be wrong here? Thanks

推荐答案

控制器动作需要查询参数(/myaction?name=myname&address=myaddress).这是默认值. 您正在将它们发送到体内.

The controller action is expecting query parameters (/myaction?name=myname&address=myaddress). That's the default. You're sending them in the body.

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

You can change the javascript to send them as query parameters. (see here: https://github.com/github/fetch/issues/256)

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

Or you can tell the controller action to take the values from the body:

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

这篇关于如何使用ASP.NET Core中的Fetch API将数据传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆