发布和接收JSON与MVC的Web API [英] Posting and receiving json with MVC Web API

查看:505
本文介绍了发布和接收JSON与MVC的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了类似的情况,以我的回答,但我有特别需求,总是从别人的问题是不同的。

I have seen similar case to mine answered but I have specific need that always differed from others problem.

我从我的html页面发送JSON数据到MVC的Web API。不幸的是我收到的数据总是空(我已经尝试了很多不同的东西在这里)。事情是我真的需要接收的数据为JSON(字符串),因为我的数据是非常复杂的,不能由Web API简单地反序列化(我有我自己的自定义解串器,做它)。

I am sending json data from my html page to the MVC Web API. Unfortunately the data I am receiving is ALWAYS null (I have tried a lot of different things here). The thing is I really need to received the data as json (string), because my data is very complex and cannot be simply deserialized by the Web API (I have my own custom deserializer that does it).

继承人的code!

首先,Web API控制器将接收的ajax post请求

First, the web api controller that will receive the ajax post request

public class ActivityController : ApiController
{
    // POST api/activity
    public string Post([FromBody]string json)
    {
    }
}

然后,AJAX请求本身

Then, the ajax request itself

$.ajax("/api/activity", {
    contentType: "application/json",
    data: { json: ko.mapping.toJSON(fusionedModel) },
    type: "POST",
    success: function (result) {
        ...
    }
});

至于数据而言,它呈现好(我用与MVC(不是Web API)和服务器接收字符串完美......现在出于某种原因,在我的web API相同的请求控制器,JSON参数始终为空。正如我以前说过,重要的是我收到的数据作为一个JSON字符串。

编辑:我发现我的问题是这样的一个重复:的 POST JSON使用MVC 4 API的Controler
但我真的不喜欢的答案......不必创建一个对象只是封装字符串是非常脏...

推荐答案

我建议你避免使用标准的人体参数作为该机制结合假定您要身体反序列化为CLR对象。试试这个,

I recommend you avoid using standard body parameter binding as that mechanism assumes that you are trying to deserialize the body into a CLR object. Try this,

public class ActivityController : ApiController
{
    // POST api/activity
    public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
    {
         var jsonString = await request.Content.ReadAsStringAsync();

         return new HttpResponseMessage();
    }
}

如果你真的想使用参数绑定,就可以做到这一点。

If you really want to use parameter binding, you can do this.

    public HttpResponseMessage Post(JToken jToken)
    {

        return new HttpResponseMessage()
        {
            Content = new StringContent(jToken.ToString())
        };
    }

这篇关于发布和接收JSON与MVC的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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