2013-06-04 120 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