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)
正在调用我的控制器操作,我可以在其中调试,但没有传递数据.这可能有什么问题?谢谢
控制器操作期待查询参数(/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)
[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 属性现在接收来自请求的值。希望这能让解决这个问题的人最终清楚。
| 归档时间: |
|
| 查看次数: |
9125 次 |
| 最近记录: |