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

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

我无法在 Unity 中使用 UnityWebRequest POST Json 格式的数据。它给出了错误

Error: HTTP/1.1 500 Internal Server Error

我正在使用在 ASP.NET Core 中制作并本地托管在 IIS Express 上的 Web 服务。

这是我在 Unity 中的 C# 代码

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

这是我的ASP.NET核心代码使用Entity Framework核心

[HttpPost]
string AddNewUser([FromBody]User user)
{
    Context.LogoQuizUsers.Add(user); // I am getting System.NullReferenceException here
    Context.SaveChanges();
    return "Inserted Id: " + user.Id;
}

Post 原始数据正文,就像您使用 Postman 或任何类似界面发送一样。 将请求的 UploadHandler 设置为 UploadHandlerRaw。添加和更改您的声明

UnityWebRequest req = UnityWebRequest.Post("http://localhost:58755/User/AddNewUser", "POST");
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(user))) as UploadHandler;

因此最终代码将是

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);
    //...
}

其余代码正确。

看看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.

帮我解决了问题