簡體   English   中英

ASP.NET Core API 中的模型綁定始終為空

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM