Web API参数始终为空
本文关键字:API 参数 Web | 更新日期: 2023-09-27 17:59:54
我的Web API中有以下方法:
[AcceptVerbs("POST")]
public bool MoveFile([FromBody] FileUserModel model)
{
if (model.domain == "abc")
{
return true;
}
return false;
}
FileUserModel
定义为:
public class FileUserModel
{
public string domain { get; set; }
public string username { get; set; }
public string password { get; set; }
public string fileName { get; set; }
}
我试图通过Fiddler调用这个,但每当我这样做时,模型总是设置为null。在Fiddler中,我已经让composer使用POST
,url在那里并且是正确的,因为VisualStudio中的调试器在调用时会中断。我设置为的请求:
User-Agent: Fiddler
Host: localhost:46992
Content-Length: 127
Content-Type: application/json
请求主体为:
"{
"domain": "dcas"
"username": "sample string 2",
"password": "sample string 3",
"fileName": "sample string 4"
}"
但每当我在调试器到达断点时运行composer时,它总是显示模型为null。
您发送的请求中缺少一个,
。此外,由于包含双引号,您实际上发送的是JSON字符串,而不是JSON对象。删除引号并添加逗号应该可以解决您的问题。
{
"domain": "dcas", // << here
"username": "sample string 2",
"password": "sample string 3",
"fileName": "sample string 4"
}
此外,由于您发布的是模型,因此不需要[FromBody]
属性。
[AcceptVerbs("POST")]
public bool MoveFile(FileUserModel model)
{
if (model.domain == "abc")
{
return true;
}
return false;
}
那应该很好。有关这方面的更多信息,请参阅此博客。
您遇到的问题是发布带有双引号的JSON数据。移除它们,它应该会起作用。
还修复了缺失的逗号:
{
"domain": "dcas",
"username": "sample string 2",
"password": "sample string 3",
"fileName": "sample string 4"
}
您需要进行如下所示的ajax调用
$(function () {
var FileUserModel = { domain: "dcas", username: "sample string 2",
password: "sample string 3", fileName: "sample string 4"};
$.ajax({
type: "POST",
data :JSON.stringify(FileUserModel ),
url: "api/MoveFile",
contentType: "application/json"
});
});
不要忘记将内容类型标记为json和服务器端的api代码
[HttpPost]
public bool MoveFile([FromBody] FileUserModel model)
{
if (model.domain == "abc")
{
return true;
}
return false;
}
在ASP.NET Web API 中发送HTML表单数据