将JSON字符串发布到WEB API [英] Post JSON string to WEB API

查看:99
本文介绍了将JSON字符串发布到WEB API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET WEB-API 2 应用程序需要有一个 POST 方法接受一个 JOSN 字符串,来自 javascript 的结构未知。


我已启用 cors GET 方法正常,但是在发送 JSON时<来自客户端的/ code> api的方法参数总是 null

这是我的 api 方法:

I have an ASP.NET WEB-API 2 app witch needs to have a POST method that accepts a JOSN string with unknown structure from javascript.
I enabled cors and GET methods works fine, however when sending JSON from the client the api's method parameter is always null.
This is my api method:

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

和我的客户方式:

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

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

So the question is how can I post an unknown JSON string from javascript and accept it as a string in my api method?

推荐答案

我编辑了你的代码,效果很好。

I edited your code and it works well.

A [FromBody ] attribute指定action参数仅来自传入HTTPRequestMessage的实体主体。

A [FromBody] attribute specifies that an action parameter comes only from the entity body of the incoming 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);
    });
}

这篇关于将JSON字符串发布到WEB API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆