.Net Core Web API不接受json字符串字段值

时间:2018-05-23 10:57:11

标签: javascript typescript asp.net-core controller asp.net-core-webapi

我有一个问题,我希望将json字符串作为字段值传递,但我一直得到"The input was not valid"。所以要清楚我的前端有一个对象,我使用下面的内容传递给我的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");
});

在我的API中,我有:

[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;
}

当我使用任何普通字符串设置j.user_filterj.user_test_filter时,我没有问题,但我想将'jsonified'字符串作为字段的值,但Web API由于某种原因不喜欢它(可能是因为它没有将它看作字符串而是看作json对象)

如果有人可以提供帮助,我将非常感激。

2 个答案:

答案 0 :(得分:0)

好久不知疲倦之后,我提出了这个解决方案&#39;。

因为@Niladri指出&#34;&#39;&#34;在JSON.stringify(j)之前是一个因素,但不是唯一需要改变的因素。主要问题实际上在控制器本身。

我以前在我的控制器中有这个:

        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;
    }

但我不得不改为:

       public async Task<string> UpdateProfileSettings(int id,[FromBody] object obj)
    {

        HttpClient clientRoute = new HttpClient();

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

        return contents;
    }

注意[FromBody] string obj[FromBody] object obj的变化以及 将StringContent(obj, Encoding.UTF8, "application/json"))更改为StringContent(obj.ToString(), Encoding.UTF8, "application/json"))

我之前的方法&#34;&#39;&#34;在JSON.stringify(j)之前,如果您的控制器[FromBody]是字符串类型,并且您不希望将类似JSON的字符串输入控制器。

如果这是一个糟糕的解释,我会道歉但是我尽了最大努力并且它对我有用

答案 1 :(得分:0)

这与mcc20自己的修复非常相似,但是我没有使该代码正常工作。 2.1框架具有问题https://github.com/aspnet/Mvc/issues/7609https://github.com/aspnet/Mvc/issues/7799。我将此JSON帖子发送到在2.1中工作的复杂类:客户端javascript不变:

var payload = JSON.stringify({ "name": document.getElementById('firstname').value, "email": document.getElementById('email').value, "captcha": grecaptcha.getResponse() });
var oReq = new XMLHttpRequest();
oReq.ContentType = "application/json";

oReq.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

        document.getElementById("update").innerHTML = this.responseText;
    }
    else document.getElementById("update").innerHTML = "not 4&200! : " + this.responseText;
};

oReq.open('POST', 'api/u');
oReq.send(payload);

并且控制器具有:

[Route("api/[controller]")]
//  [ApiController] // works either way
public class UController : ControllerBase
{
    [HttpPost]
    public async Task<string> signUp()
    {
        String body;
        using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
        {
            body = await reader.ReadToEndAsync();
        }

        UserSignup user = JsonConvert.DeserializeObject<UserSignup>(body);

        return user.email;
    }
}

我正在尝试类似([FromBody] UserSignup user)的操作,得到Mvc.SerializableError和“输入无效”。即将发布在https://github.com/Hover-Us/