如何将参数从Ajax请求传递到Web API控制器?
我正在寻找如何在ASP.Net Core中将参数从Ajax请求传递到Web API控制器的方式,如经典ASP中的query string
。 我在下面尝试过,但没有奏效。如何将参数从Ajax请求传递到Web API控制器?
查看:
"ajax":
{
"url": "/api/APIDirectory/[email protected]"
"type": "POST",
"dataType": "JSON"
},
控制器:
[HttpPost]
public IActionResult GetDirectoryInfo(string reqPath)
{
string requestPath = reqPath;
// some code here..
}
任何人都可以请告知可在asp.net核心Web API来实现这一目标的途径?
"ajax":
{
"url": "/api/APIDirectory/GetDirectoryInfo"
"type": "POST",
"dataType": "JSON",
"data": {"reqPath":"@ViewBag.Title"}
}
编辑的结合上写着: 如果我们使用的查询字符串,我们可以使用的类型作为GET。
但是我们使用的是POST方法,所以我们需要将参数传递给数据。
虽然此代码片段可能会解决问题,但[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 –
谢谢。我已经添加了解释。 –
投递查询字符串数据使用内容类型application/x-WWW窗体-urlencoded
$.ajax({
type: "POST",
url: "/api/APIDirectory/GetDirectoryInfo?reqPath=" + @ViewBag.Title,
contentType: "application/x-www-form-urlencoded"
});
同时,确保了ajax语法是正确的(我使用jQuery在我的例子)和@ViewBag不包含在字符串中。
然后在控制器中添加[FromUri]参数,以确保从URI
[HttpPost]
public IActionResult GetDirectoryInfo([FromUri]string reqPath)
{
string requestPath = reqPath;
// some code here..
}
确保'@ ViewBag.Title'不为空。 – Xyroid