I cannot POST data in Json Format using UnityWebRequest in Unity. It gives error
Error: HTTP/1.1 500 Internal Server Error
I am using Webservice made in ASP.NET Core and hosted locally on IIS Express.
Here is my C# Code in Unity
public class AddUsers : MonoBehaviour
{
IEnumerator addOrUpdateUser()
{
User user = new User()
{
Id = "0001",
Name = "John",
}
UnityWebRequest req = UnityWebRequest.Post("http://localhost:58755/User/AddNewUser", JsonConvert.SerializeObject(user));
req.SetRequestHeader("Content-Type", "application/json");
req.certificateHandler = new BypassCertificate();
yield return req.SendWebRequest();
if (req.isNetworkError || req.isHttpError || req.isError)
print("Error: " + req.error);
print(req.downloadHandler.text);
}
}
[Serializable]
public class UserDetails
{
public string Id { get; set; }
public string Name { get; set; }
}
Here is my ASP.NET Core Code using Entity Framework Core
[HttpPost]
string AddNewUser([FromBody]User user)
{
Context.LogoQuizUsers.Add(user); // I am getting System.NullReferenceException here
Context.SaveChanges();
return "Inserted Id: " + user.Id;
}
Post data as raw - body just as you would send using Postman or any similar interface. Set Request's UploadHandler
as UploadHandlerRaw
. Add and Change your statement
UnityWebRequest req = UnityWebRequest.Post("http://localhost:58755/User/AddNewUser", "POST");
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(user))) as UploadHandler;
Hence the final code will be
IEnumerator addOrUpdateUser()
{
//...
UnityWebRequest req = UnityWebRequest.Post("http://localhost:58755/User/AddNewUser", "POST");
req.SetRequestHeader("Content-Type", "application/json");
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(user))) as UploadHandler;
req.certificateHandler = new BypassCertificate();
yield return req.SendWebRequest();
if (req.isNetworkError || req.isHttpError || req.isError)
print("Error: " + req.error);
print(req.downloadHandler.text);
//...
}
Rest of the code is correct.
Look at this topic
Inside the Unity editor: Go to Window -> Package Manager. In the topbar of the new window, search the "Packages: XXXXXX" drop-down and select "Unity Registry". Search the "WebGl publisher" and install / import it.
IIIFFF the package doesn't appear: In the same Package manager windows, click the "+" button -> Add from git. Add the following:
com.unity.connect.share
This will automatically add the WebGL Publisher.
It helped me to resolve the problem
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.