我无法在Unity中使用UnityWebRequest以Json格式POST数据。它给出错误
错误:HTTP/1.1 500内部服务器错误
我使用的是ASP.NET Core中制作的Web服务,该服务在IIS Express上本地托管。
这是我在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核心代码
[HttpPost]
string AddNewUser([FromBody]User user)
{
Context.LogoQuizUsers.Add(user); // I am getting System.NullReferenceException here
Context.SaveChanges();
return "Inserted Id: " + user.Id;
}
将数据作为原始主体发布,就像使用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);
//...
}
其余代码正确。
看看这个主题
Unity编辑器内部:转到窗口->程序包管理器。在新窗口的顶栏中;包装:XXXXXX";下拉并选择";Unity Registry";。搜索";WebGl发布者";并安装/导入。
IIIFFF包裹未出现:在相同的软件包管理器窗口中+"按钮->从git添加。添加以下内容:
com.unity.connect.share
这将自动添加WebGL发布服务器。
它帮助我解决了问题