我嘗試使用 restSharp 檢索我作為 json 發送到我的 API 控制器的模型,但是當我在控制器中接收到 TestCard 物件時它始終為空,這是為什么呢?
模型
public class TestCard
{
public int OrderId { get; set; }
public List<Person> Persons { get; set; }
}
public class Person
{
public string Name { get; set; }
public string Adress { get; set; }
public string Adress2 { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
測驗站
var personList = new List<Person>();
personList.Add(new Person
{
Name = "John Doe",
Adress = "West Park Ave",
PostalCode = "123",
City = "NY",
Country = "US"
});
personList.Add(new Person
{
Name = "Sandra Doe",
Adress = "West Park Ave",
PostalCode = "123",
City = "NY",
Country = "US"
});
var order = new TestCard() { OrderId = 1, Persons = personList };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient("https://localhost:44336/api/card/");
client.Authenticator = new HttpBasicAuthenticator("myusername", "mypassword");
var request = new RestRequest("Add", Method.Post);
request.AddBody(JsonConvert.SerializeObject(order));
request.AddHeader("Content-Type", "application/json");
Task<RestResponse> response = client.ExecuteAsync(request);
if (response.Result.StatusCode == HttpStatusCode.Created)
{
Response.Write("OK!");
}
控制器
[Route("api/Card/Add")]
[AcceptVerbs("GET", "POST")]
[HttpPost]
public IHttpActionResult Add([FromBody] TestCard model)
{
return Ok();
}
uj5u.com熱心網友回復:
當您使用 request.addbody 時,您不必序列化物件
request.AddBody(order);
和恕我直言,洗掉 [AcceptVerbs("GET", "POST")] 因為你已經 [HttpPost]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429802.html
上一篇:json.decoder.JSONDecodeError:額外資料:第1行第1列第139811列(字符139810)
下一篇:在C#中動態構造JSON值
