Javascript 将 JSON 字符串发布到 WEB API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36567136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:13:46  来源:igfitidea点击:

Post JSON string to WEB API

javascriptjsonasp.net-web-api2

提问by Yoav

I have an ASP.NET WEB-API 2app witch needs to have a POSTmethod that accepts a JOSNstringwith unknown structure from javascript.
I enabled corsand GETmethods works fine, however when sending JSONfrom the client the api's method parameter is always null.
This is my apimethod:

我有一个ASP.NET WEB-API 2应用程序女巫需要一个POST方法来接受JOSNstring来自javascript.
我启用cors并且GET方法工作正常,但是JSON从客户端发送时,api 的方法参数始终为null.
这是我的api方法:

//parameters i tried:
//[FromBody]string model
//[FromBody]dynamic model
//dynamic model
public HttpResponseMessage Post(string model)
{
    return new HttpResponseMessage()
    {
        Content = new StringContent("POST: Test message: " + model)
    };
}

and my client method:

和我的客户端方法:

function sendRequest()
{
    var Test = {"Name":"some name"};
    var method = $('#method').val();

    $.ajax({
        type: method,
        url: serviceUrl,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(Test)               
    }).done(function (data)
    {
        $('#value1').text(data);
    }).error(function (jqXHR, textStatus, errorThrown)
    {
        $('#value1').text(jqXHR.responseText || textStatus);
    });
}

So the question is how can I post an unknown JSON stringfrom javascriptand accept it as a string in my apimethod?

所以问题是如何在我的方法中发布未知JSON string信息javascript并将其作为字符串接受api

回答by Alex Nguyen

I edited your code and it works well.

我编辑了你的代码,它运行良好。

A [FromBody] attribute specifies that an action parameter comes only from the entity body of the incoming HTTPRequestMessage.

[FromBody] 属性指定操作参数仅来自传入 HTTPRequestMessage 的实体主体。

public class TestApiController : ApiController
    {
        // POST api/<controller>
        [HttpPost]
        public HttpResponseMessage Post([FromBody]string value)
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("POST: Test message: " + value)
            };
        }

    }

function sendRequest() {
    var Test = { "Name": "some name" };

    $.ajax({
        type: "POST",
        url: "api/TestApi",
        data: { '': JSON.stringify(Test) }
    }).done(function (data) {
        alert(data);
    }).error(function (jqXHR, textStatus, errorThrown) {
        alert(jqXHR.responseText || textStatus);
    });
}

回答by Federico Dipuma

Either treat the POST request as a generic HTTP request, and manually parse the body:

将 POST 请求视为通用 HTTP 请求,并手动解析正文:

public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
    var jsonString = await request.Content.ReadAsStringAsync();

    // deserialize the string, or do other stuff

    return new HttpResponseMessage(HttpStatusCode.OK);
}

Or use a generic JToken, and let the serializer do the rest:

或者使用通用 JToken,让序列化程序完成剩下的工作:

public HttpResponseMessage Post([FromBody] JToken model)
{
    DoStuff(model);

    var myField = model["fieldName"];

    return new HttpResponseMessage(HttpStatusCode.OK);
}

Notes: this way you do not need to alter client-side code, because you are still POSTing json data, not a generic string, which is semantically the right choice if you expect your client to post serialized JSON objects.

注意:这样您就不需要更改客户端代码,因为您仍在发布 json 数据,而不是通用字符串,如果您希望您的客户端发布序列化的 JSON 对象,这在语义上是正确的选择。

References:

参考:

http://bizcoder.com/posting-raw-json-to-web-api

http://bizcoder.com/posting-raw-json-to-web-api