ASP.NET 来自 JavaScript 的 HTTPOST 的核心空参数
ASP.NET Core empty parameters by HTTPOST from JavaScript
我正在创建一个 ASP.NET 核心 WepApp,但我无法将数据从 javascript 发送到我的服务器。
HTML:
<button onclick="sendData()">Send Data to the Server</button>
JavaScript:
function sendData() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Cockpit/Index", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"Test": "value"
}));
};
ASP.NET核心
namespace Paragliding.Controllers
{
public class CockpitController : Controller
{
[HttpPost]
public IActionResult Index(Test test)
{
return Json(test);
}
public IActionResult Index()
{
return View();
}
}
}
Class 测试
namespace Paragliding.Models
{
public class Test
{
public string TestValue { set; get; }
}
}
当我按下按钮向服务器发送数据时,调试可以看到,他跳转到了方法里面
[HttpPost]
public IActionResult Index(Test test)
但参数test始终为空
the parameter test is always empty
您可以尝试修改如下代码
function sendData() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhr.open("POST", "/Cockpit/Index", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"TestValue": "blabla here"
}));
};
将[FromBody]
属性应用于参数
[HttpPost]
public IActionResult Index([FromBody]Test test)
{
return Json(test);
}
测试结果
我正在创建一个 ASP.NET 核心 WepApp,但我无法将数据从 javascript 发送到我的服务器。
HTML:
<button onclick="sendData()">Send Data to the Server</button>
JavaScript:
function sendData() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Cockpit/Index", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"Test": "value"
}));
};
ASP.NET核心
namespace Paragliding.Controllers
{
public class CockpitController : Controller
{
[HttpPost]
public IActionResult Index(Test test)
{
return Json(test);
}
public IActionResult Index()
{
return View();
}
}
}
Class 测试
namespace Paragliding.Models
{
public class Test
{
public string TestValue { set; get; }
}
}
当我按下按钮向服务器发送数据时,调试可以看到,他跳转到了方法里面
[HttpPost]
public IActionResult Index(Test test)
但参数test始终为空
the parameter test is always empty
您可以尝试修改如下代码
function sendData() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhr.open("POST", "/Cockpit/Index", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"TestValue": "blabla here"
}));
};
将[FromBody]
属性应用于参数
[HttpPost]
public IActionResult Index([FromBody]Test test)
{
return Json(test);
}
测试结果