Home » Javascript » .Net Core Web API not accepting a json string field value

.Net Core Web API not accepting a json string field value

Posted by: admin August 19, 2018 Leave a comment

Questions:

I have a problem whereby I would like to pass a json string as a field value but I keep getting "The input was not valid". So to be clear I have an object in my front end that I use the below to pass to my API:

let j: Settings = {} as Settings;
j.user_settings_ID = object.user_settings_ID;
j.user_ID = object.user_ID;
j.user_filter = JSON.stringify(object.user_filter);
j.user_test_filter = JSON.stringify(object.user_test_filter);

fetch('api/Profile/UpdateProfileSettings/?id=' + object.user_settings_ID, {
    method: 'put',
    headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization': 'Bearer ' + sessionStorage.getItem('token')
    },
    body: "'" + JSON.stringify(j) + "'",
}).then(data => {
    if (!data.ok) {
        alert("Failed");
    }           
}).catch((ex) => {
    alert("Failed");
});

In my API I have:

[HttpPut("[action]")]
public async Task<string> UpdateProfileSettings(int id, [FromBody] string obj)
{
    HttpClient clientRoute = new HttpClient();

    var response = await clientRoute.PutAsync("https://something.com/api/UserSettings/put/" + id, new StringContent(obj, Encoding.UTF8, "application/json"));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

I don’t have a problem when I set the j.user_filter and j.user_test_filter with any normal string, but I would like to put the 'jsonified' string as the value for the field, but the Web API doesn’t like it for some reason (probably because it isn’t seeing it as a string but a json object perhaps)

If someone could help I would be most grateful.

Answers: