Posting and receiving json with MVC Web API

2019-09-18 09:55发布

问题:

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

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).

Heres the code!

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

Then, the ajax request itself

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

As far as the data is concerned, it is rendered well (I've used that same request with MVC (not Web Api) and the server was receiving the string perfectly... now for some reason, in my web api controller, the "json" param is ALWAYS null. As I said before, it is IMPORTANT that I receive the data as a json string.

EDIT : I found that my question is a duplicate of this one : POST JSON with MVC 4 API Controller But I really don't like the answer... having to create an object just to encapsulate the string is very dirty...

回答1:

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


回答2:

Please try to use the [HttpPost] Attribute that can be located on System.Web.Http;

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


回答3:

I could be wrong here, but it looks like you haven't included your action in the post URL. Try changing

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

To

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