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);
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0