2

How I do a post with json value to a ASP.NET MVC 4 Web Api Controller? I tried it several ways, but I can't make it works.

First, my simplified Controller action:

[HttpPost]
public Interaction Post(Interaction filter)
{
     return filter;
}

And my post method with Unity3D WWW:

public string GetJson(string url, WWWForm form)
{
    var www = new WWW(url, form);

    while (!www.isDone) { };

    return www.text;
}

Where my WWWForm is:

var form = new WWWForm();
form.AddField("filter", interaction);

I tried specify the header, like:

public string GetJson(string url, byte[] data)
{
    var header = new Hashtable();
    header.Add("Content-Type", "text/json");

    var www = new WWW(url, data, header);

    while (!www.isDone) { };

    return www.text;
}

I really tried to solve this by more than ten different ways and I always get the same result:

Debug.Log(input); // {"Id":15,"Name":"Teste","Description":"Teste","Value":0.0,"Time":10.0}
Debug.Log(output); // {"Id":0,"Name":null,"Description":null,"Value":0.0,"Time":0.0}

Any direction will be helpful. Thanks!

1
  • Try adding this to your action if (!ModelState.IsValid) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState)); } and see if you get any model state errors in response. Commented Jun 4, 2013 at 6:36

1 Answer 1

6

Do not use WWWForm to post JSON. Use something like this.

string input = "You JSON goes here";

Hashtable headers = new Hashtable();
headers.Add("Content-Type", "application/json");

byte[] body = Encoding.UTF8.GetBytes(input);

WWW www = new WWW("http://yourserver/path", body, headers);

yield www;

if(www.error) {
         Debug.Log(www.error);
}
else {
        Debug.Log(www.text);
}

Assuming JSON string in input is like this,

{"Id":15,"Name":"Teste","Description":"Teste","Value":0.0,"Time":10.0}

you will need a class like this

public class Interaction
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string Description { get; set; }
   public string Teste { get; set; }
   // other properties
}

for the action method like this to work

public Interaction Post(Interaction filter)
Sign up to request clarification or add additional context in comments.

3 Comments

:It works! Thanks a lot. For everyone... Don't forget to configure the crossdomain file to accept these requests. See the article
Y i am getting error error CS0103: The name `Encoding' does not exist in the current context
Because you don't have a using System.Text; at the beginning if your file @Sona?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.