Unity3D张贴JSON到ASP.NET MVC 4网页API [英] Unity3D post a json to ASP.NET MVC 4 Web Api

查看:158
本文介绍了Unity3D张贴JSON到ASP.NET MVC 4网页API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用JSON值后到ASP.NET MVC 4的Web API控制器?
我试了几种方法,但我不能让它工作。

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:

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}

您将需要一个像这样的类

you will need a class like this

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网页API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆