Unity3D 将 json 发布到 ASP.NET MVC 4 Web Api [英] Unity3D post a json to ASP.NET MVC 4 Web Api
问题描述
我如何向 ASP.NET MVC 4 Web Api 控制器发布带有 json 值的帖子?我尝试了几种方法,但我无法使其正常工作.
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;
}
以及我使用 Unity3D WWW 的 post 方法:
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;
}
我的 WWWForm 在哪里:
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!
推荐答案
不要使用 WWWForm 发布 JSON.使用这样的东西.
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);
}
假设输入中的JSON字符串是这样的,
Assuming JSON string in input is like this,
{"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
}
为了让这样的动作方法起作用
for the action method like this to work
public Interaction Post(Interaction filter)
这篇关于Unity3D 将 json 发布到 ASP.NET MVC 4 Web Api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!