[英]Web API parameter is always null
我的 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 在那里並且正確,因為 Visual Studio 中的調試器在調用時中斷。 我設置為的請求:
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 時,它總是顯示模型為空。
您在發送的請求中缺少,
。 此外,由於包含雙引號,您實際上發送的是 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;
}
那應該沒問題。 有關這方面的更多信息,請參閱此博客。
你需要像下面這樣進行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;
}
您遇到的問題是您正在發布帶有雙引號的 JSON 數據。 刪除它們,它應該可以工作。
還要修復丟失的逗號:
{
"domain": "dcas",
"username": "sample string 2",
"password": "sample string 3",
"fileName": "sample string 4"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.