正如您在標題中看到的,此方法發送字串但不發送我的類物件。此方法在 Windows 表單應用程式中正常作業。方法:
async public Task<bool> PostHttp()
{
using (var client = new HttpClient())
{
RegModel model = new RegModel()
{
UserMail = "ca35",
UserPass = "1111"
};
//string model = "denemeGe";
client.BaseAddress = new Uri("http://localhost:5070/");
string postData = JsonConvert.SerializeObject(model);
//string postData = JsonUtility.ToJson(model);
Debug.Log(postData);
var content = new StringContent(postData, Encoding.UTF8, "application/json");
var result = await client.PostAsync("api/doPost",content);
string resultContent = await result.Content.ReadAsStringAsync();
Debug.Log(resultContent);
return true;
}
}
我的課:
public class RegModel
{
public string UserMail;
public string UserPass;
}
和 API:
[ApiController]
[Route("api/RemoteOperations")]
public class RegController : ControllerBase
{
[HttpGet]
[Route("/api/doGet")]
public RegModel Get()
{
var _regModel = new RegModel()
{
UserMail = "deneme",
UserPass ="denemepass"
};
return _regModel;
}
[HttpPost]
[Route("/api/doPost")]
public string Post(RegModel regModel)
{
string result = regModel.UserMail;
return "ok " result;
}
}
當我嘗試像這樣發布我的模型 json 除錯時:
{"UserMail":"ca35","UserPass":"1111"}
但是 RegModel.userMail 和 RegModel.userPass 回傳 null。問題是什么 ?
uj5u.com熱心網友回復:
如果您使用的是新的 Web 應用服務器,和/或您的服務器使用 System.Text.Json 作為它的 JSON 序列化程式,那么您可以通過以下兩種方式之一解決該問題:
第一種是使用屬性而不是欄位。如果您的客戶端序列化程式希望您使用欄位而不是屬性,這可能是一個問題,在這種情況下,您需要定義模型兩次,一次在客戶端使用欄位,在服務器端使用屬性:
public class RegModel
{
public string UserMail { get; set; }
public string UserPass { get; set; }
}
第二種方法是允許 System.Text.Json 通過添加JsonSerializerOptions.IncludeFields
選項來讀取服務器上的欄位:
// Add services to the container.
builder.Services.AddControllers ( )
.AddJsonOptions ( options => options.JsonSerializerOptions.IncludeFields = true );
uj5u.com熱心網友回復:
網路不能發送物件。您可以將物件轉換為 JSON 或 XML 格式并通過網路發送。準備一個模型來接收資料到服務器并使用這個模型接收資料。我想你明白
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/511526.html
上一篇:成員變數只維護函式范圍的賦值