[SOLVED] Cannot POST data using UnityWebRequest in Unity, it gives Error: HTTP/1.1 500 Internal Server Error

Issue

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;
}

Solution

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.

Answered By – Junaid Pathan

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *