POST参数在Unity3d中始终为null

时间:2017-02-13 19:15:42

标签: c# rest unity3d asp.net-web-api

我在asp.net web api2服务器上有这个代码:

[HttpPost]
    [AllowAnonymous]
    public IHttpActionResult Login(RequestLogin args)
    {
        //work
    }

我尝试使用参数“高级REST客户端”发送帖子请求:

http://localhost:54382/api/Home/Login
application/json
{"Name":"asd","DeviceId":"818cd41169410e6f20ef55b2917d0e15e5cf072f"}

......它完美无缺! Login方法中的args为完整

但是 如果我从 Unity3d

尝试此操作
UnityWebRequest www;
var url = http://localhost:54382/api/Home/Login;
string jsonObj = JsonUtility.ToJson(request.args);
Debug.Log(jsonObj); //{"Name":"asd","DeviceId":"818cd41169410e6f20ef55b2917d0e15e5cf072f"}
www = UnityWebRequest.Post(url, jsonObj);
www.SetRequestHeader("Content-Type", "application/json; charset=utf-8");
yield return www.Send();

Login方法中的args包含 null 值。

[Serializable]
    public class RequestLogin
    {
        public string Name;
        public string DeviceId;
    }

我摔了几天脑袋。请帮帮我

3 个答案:

答案 0 :(得分:8)

将Unity升级到2017.3.0版后,我遇到了完全相同的问题。对我有用的修复是将UnityWebRequest.chunkedTransfer设置为false。 我的帖子方法如下:

public static UnityWebRequest PostJson(string url, string json)
    {
        UnityWebRequest request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
        byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(json);
        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        request.chunkedTransfer = false;
        return request;
    }

答案 1 :(得分:1)

通过UnityWebRequest阅读,您似乎可以选择这样做:

WWWForm form = new WWWForm();
form.AddField("Name", "asd");
form.AddField("DeviceId", "818cd41169410e6f20ef55b2917d0e15e5cf072f");

www = UnityWebRequest.Post(url, form);

您可以按照文档的含义进行尝试吗?

答案 2 :(得分:0)

我通过从“UnityWebRequest”返回旧的“WWW”方法解决了一个问题。 例: Unity3D post a json to ASP.NET MVC 4 Web Api