![](/img/trans.png)
[英]In ASP.Net Core 5 MVC Controller, when passed a JSON object FromBody that contains a decimal the model is always null
[英]Model binding in ASP.NET Core API are always null
我有一個簡單的 ASP.NET Core API,我使用 javascript 的 fetch 方法調用它。 但是SearchString屬性類型的輸入變量模型始終為空。
出於某種原因,當我使用 Postman 調用它時,它按預期工作,但不能從 javascript 調用。
應用程序接口:
[HttpPost]
public async Task<IActionResult> Search([FromBody] BasicSearchModel model)
{
....
}
基本搜索模型.cs :
public interface IBasicSearchModel
{
string SearchString { get; set; }
}
public class BasicSearchModel : IBasicSearchModel
{
public string SearchString { get; set; }
}
JavaScript :
const WebRequest = async (controller = "API", action, query = {}, data = {}, method = RequestMethods.POST, mode = RequestModes.SameOrigin, creds = RequestCredentials.SameOrigin, headers = {
"Content-Type": "application/json",
"Accept": "application/json"
}) => {
const GetUrl = () => {
var result = "/" + controller + "/" + action;
var i = 0;
for (var q in query) {
if (i === 0) {
result += "?";
} else {
result += "&";
}
result += q[0] + "=" + q[1];
i++;
}
return result;
}
await fetch(GetUrl(), {
method: method,
headers: headers,
// @ts-ignore
credentials: creds.toLowerCase(),
// @ts-ignore
body: data,
// @ts-ignore
mode: mode.toLowerCase(),
})
.then(response => {
if (response.ok) {
return new RequestResult(response);
} else {
throw new Error("Request failed: " + response.status + "; " + response.statusText);
}
})
.catch(error => {
throw new Error("Error: " + error.statusText);
});
};
JavaScript 調用:
var result = await WebRequest("Identity", "Search", null, { SearchString: str });
請求:
標頭:接受:“application/json”,“Content-Type”:“application/json”
方法:“POST”
正文:SearchString在: “測試儀”
它在使用 Postman 調用時按預期工作,很可能是因為它的格式正確。
搜索字符串:“測試員”
不是有效的 JSON
將要發送的數據字符串化
await fetch(GetUrl(), {
method: method,
headers: headers,
// @ts-ignore
credentials: creds.toLowerCase(),
// @ts-ignore
body: JSON.stringify(data), //<--NOTE
// @ts-ignore
mode: mode.toLowerCase(),
})
以便模型綁定器解析正確的格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.