Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unity3D将json发布到ASP.NET MVC 4 Web Api_Json_Post_Asp.net Web Api_Unity3d - Fatal编程技术网

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

Unity3D将json发布到ASP.NET MVC 4 Web Api,json,post,asp.net-web-api,unity3d,Json,Post,Asp.net Web Api,Unity3d,如何向ASP.NET MVC 4 Web Api控制器发送带有json值的帖子? 我试了好几种方法,但都不能成功 首先,我的简化控制器操作: [HttpPost] public Interaction Post(Interaction filter) { return filter; } 以及我在Unity3D WWW上发布的方法: public string GetJson(string url, WWWForm form) { var www = new WWW(url,

如何向ASP.NET MVC 4 Web Api控制器发送带有json值的帖子? 我试了好几种方法,但都不能成功

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

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

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

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

如果(!ModelState.IsValid){抛出新的HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,this.ModelState));}请尝试将其添加到操作
中,并查看您是否在响应中得到任何模型状态错误。注意:它工作正常!谢谢。对每个人来说。。。不要忘记配置跨域文件以接受这些请求。请参阅Y i Get error CS0103:名称“Encoding”在当前上下文中不存在,因为您没有使用System.Text的
如果您的文件@Sona在开头?