我有一个简单的 ASP.NET Core API,我使用 javascript 的 fetch 方法调用它。但 SearchString 属性类型的输入变量 model 始终为 null。
当我使用 Postman 调用它时,它按预期工作,但由于某种原因,不是从 javascript 调用它。
API:
[HttpPost]
public async Task<IActionResult> Search([FromBody] BasicSearchModel model)
{
....
}
BasicSearchModel.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”
方法: “发布”
正文: 搜索字符串:“测试员”
最佳答案
使用 Postman 调用时它会按预期工作,很可能是因为它的格式正确。
SearchString: "tester"
不是有效的 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(),
})
以便模型绑定(bind)器能够解析正确的格式。
关于javascript - ASP.NET Core API 中的模型绑定(bind)始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59265148/