【问题标题】:Unity3D post a json to ASP.NET MVC 4 Web ApiUnity3D 将 json 发布到 ASP.NET MVC 4 Web Api
【发布时间】:2013-05-30 10:23:47
【问题描述】:

如何将 json 值发布到 ASP.NET MVC 4 Web Api 控制器? 我尝试了几种方法,但我无法使其工作。

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

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

还有我使用 Unity3D WWW 的 post 方法:

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}

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

【问题讨论】:

  • 尝试将此添加到您的操作if (!ModelState.IsValid) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState)); } 中,看看您是否收到任何模型状态错误作为响应。

标签: json post asp.net-web-api unity3d


【解决方案1】:

不要使用 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)

【讨论】:

  • :有效!非常感谢。对于每个人...不要忘记配置跨域文件以接受这些请求。见article
  • Y 我收到错误错误 CS0103:当前上下文中不存在名称“编码”
  • 因为如果你的文件@Sona 开头没有using System.Text;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 2015-05-27
  • 1970-01-01
  • 2012-07-27
相关资源
最近更新 更多