[英]Post Request not receiving any Data
I am trying to make a PostRequest from Unity that creates a new account in a database.我正在尝试从 Unity 发出 PostRequest,以在数据库中创建一个新帐户。 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.当我运行 Post Request 功能(单击提交按钮)时,会在数据库中创建一个新帐户,但所有值都为空。 I am unable to get any of the data at the controller.我无法在控制器上获取任何数据。 I am sending the data as a string in Json format.我将数据作为 Json 格式的字符串发送。 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来自 Unity 的 PostRequest
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
.您正在发送类型为application/json
内容正文。 Form datas are sent via x-www-form-urlencoded
.表单数据通过x-www-form-urlencoded
。 You need to change parameter binder [FromForm]
to [FromBody]
on your controller action.您需要在控制器操作[FromBody]
参数绑定器[FromForm]
更改为[FromBody]
。
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.其次, " { \\"highScores\\":[],\\"lazyLoader\\":{},\\"userName\\":user\\",\\"password\\":null,\\"displayName\\":null} "
是不是有效的 Json。当您更改为FromBody
绑定程序时,反序列化器将抛出序列化异常。您还需要修复 json 数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.