简体   繁体   中英

Post Request not receiving any Data

I am trying to make a PostRequest from Unity that creates a new account in a database. When I run the Post Request function(click the submit button), a new Account is created in the database but all of the values are null. I am unable to get any of the data at the controller. I am sending the data as a string in Json format. Any help is appreciated.

Controller:

    [HttpPost]
    public string Post([FromForm] Account data )
    {
        Console.WriteLine("Data user name: " +data.userName);
        db.Accounts.Add(data);
        db.SaveChanges();
        Console.WriteLine(data);
        return "success";
    }

PostRequest from Unity

    public void AddAccount()
    {

    WebRequest request = (HttpWebRequest)WebRequest.Create("https://localhost:44301/accounts" );
    request.Method = "POST";

    string json = " { \"highScores\":[],\"lazyLoader\":{},\"userName\":user\",\"password\":testpassword",\"displayName\":name"} ";
    byte[] byteArray = Encoding.UTF8.GetBytes(json);

    request.ContentType = "application/json; charset=UTF-8";

    request.ContentLength = byteArray.Length;

    Stream dataStream = request.GetRequestStream();

    dataStream.Write(byteArray, 0, byteArray.Length);

    dataStream.Close();

    WebResponse response = request.GetResponse();

    Debug.Log(((HttpWebResponse)response).StatusDescription);

    using (dataStream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(dataStream);

        string responseFromServer = reader.ReadToEnd();

        Debug.Log(responseFromServer);
    }

}

You're sending content body with type application/json . Form datas are sent via x-www-form-urlencoded . You need to change parameter binder [FromForm] to [FromBody] on your controller action.

Secondly, " { \\"highScores\\":[],\\"lazyLoader\\":{},\\"userName\\":user\\",\\"password\\":null,\\"displayName\\":null} " is not a valid Json. When you change to FromBody binder, the deserializer will throw serialization exception. You need to fix the json data, also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM