簡體   English   中英

在C#中對日期時間字段進行序列化時,模型始終為null-Restsharp

[英]Model is always null when date-time field is serialized in C# - Restsharp

我在使用C#進行簡單的序列化和反序列化時遇到問題。

我正在使用RestSharp調用webapi方法(REST方法)。

型號是:

public class MyModel
{
  public DateTime date {get;set;}
}

控制器方式:

[RoutePrefix("Test")]
public class ValuesController : ApiController
{
    [Route("~/Date")]
    [HttpPost]
    public IHttpActionResult Post([FromBody] MyModel model)
    {
        if (model == null)
          return NotOk();

        return Ok();
    }
}

但不幸的是,使用xml時,該model始終為null。

Restsharp客戶端:

var restRequest = new RestRequest(@"http://localhost:50099/Date", Method.POST)
{
      RequestFormat = DataFormat.Xml,
};

restRequest.AddBody(new MyModel(), "");

---->當數據格式為xml ,模型為null。

Restsharp客戶端:

var restRequest = new RestRequest(@"http://localhost:50099/Date", Method.POST)
{
      RequestFormat = DataFormat.Json,
};

restRequest.AddBody(new MyModel(), "");

----->當數據格式為json時,模型不為null。 date屬性是默認屬性。

在這里回答。

簡而言之,在初始化Json serializer時,我將DataContractSerializer設置為true。 DataContractSerializer預期日期為epoch格式,因此是問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM