Unity3D将json发布到ASP.NET MVC 4 Web Api

rob*_*osa 2 post json unity-game-engine asp.net-web-api

我如何使用json值发布ASP.NET MVC 4 Web Api控制器?我尝试了几种方法,但我不能使它有效.

首先,我的简化控制器动作:

[HttpPost]
public Interaction Post(Interaction filter)
{
     return filter;
}
Run Code Online (Sandbox Code Playgroud)

和Unity3D WWW的post方法:

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

    while (!www.isDone) { };

    return www.text;
}
Run Code Online (Sandbox Code Playgroud)

我的WWWForm在哪里:

var form = new WWWForm();
form.AddField("filter", interaction);
Run Code Online (Sandbox Code Playgroud)

我尝试指定标题,如:

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;
}
Run Code Online (Sandbox Code Playgroud)

我真的试图通过十多种不同的方式解决这个问题,我总是得到相同的结果:

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}
Run Code Online (Sandbox Code Playgroud)

任何方向都会有所帮助.谢谢!

Bad*_*dri 6

不要使用WWWForm发布JSON.使用这样的东西.

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);
}
Run Code Online (Sandbox Code Playgroud)

假设输入中的JSON字符串是这样的,

{"Id":15,"Name":"Teste","Description":"Teste","Value":0.0,"Time":10.0}
Run Code Online (Sandbox Code Playgroud)

你需要一个这样的课程

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
}
Run Code Online (Sandbox Code Playgroud)

对于像这样的动作方法来工作

public Interaction Post(Interaction filter)
Run Code Online (Sandbox Code Playgroud)

  • 因为你的文件@Sona在开头没有`using System.Text;`? (3认同)