SteinTech
SteinTech

Reputation: 4068

Model binding in ASP.NET Core API are always null

I have a simple ASP.NET Core API which I invoke with javascript's fetch method. But the input variable model of type SearchString property is always null.

It works as expected when I invoke it using Postman, but not from javascript, for some reason.

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 call:

var result = await WebRequest("Identity", "Search", null, { SearchString: str });

Request:

Headers: Accept: "application/json", "Content-Type": "application/json"

Method: "POST"

Body: SearchString: "tester"

Upvotes: 2

Views: 900

Answers (1)

Nkosi
Nkosi

Reputation: 246998

It works as expected when invoked using Postman most likely because it is in the correct format.

SearchString: "tester"

is not valid JSON

Stringyfy the data to be sent

await fetch(GetUrl(), {
    method: method,
    headers: headers,
    // @ts-ignore
    credentials: creds.toLowerCase(),
    // @ts-ignore
    body: JSON.stringify(data), //<--NOTE
    // @ts-ignore
    mode: mode.toLowerCase(),
})

so that it is in the correct format to be parsed by the model binder.

Upvotes: 3

Related Questions