Unity3D post a json to ASP.NET MVC 4 Web Api

后端 未结 1 1854
终归单人心
终归单人心 2021-01-01 08:19

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:

1条回答
  •  有刺的猬
    2021-01-01 08:57

    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)
    

    0 讨论(0)
提交回复
热议问题