2013-06-04 121 views
1

我如何使用json值发布到ASP.NET MVC 4 Web Api控制器? 我尝试了几种方法,但我无法使它成功。Unity3D发布json到ASP.NET MVC 4 Web Api

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

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

和我交法Unity3D WWW:

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

    while (!www.isDone) { }; 

    return www.text; 
} 

凡我WWWForm是:

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

我试图指定头,如:

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

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

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} 

任何方向将是有益的。谢谢!

+0

尝试添加到您的行动'if(!ModelState.IsValid) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,this.ModelState)); }'看看你是否得到任何模型状态错误的回应。 –

回答

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

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

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

你需要这样的

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 
} 

一类这样的操作方法工作

public Interaction Post(Interaction filter) 
+0

:它的工作原理!非常感谢。对于每个人...不要忘记配置跨域文件来接受这些请求。请参阅[文章](http://www.senocular.com/pub/adobe/crossdomain/policyfiles.html) – robsonrosa

+0

Y我得到错误错误CS0103:名称'编码'在当前上下文中不存在 – Sona

+3

因为你如果你的文件@Sona在开始时没有'使用System.Text;'? – Bart