簡體   English   中英

當dto具有數據注釋時,PutAsJsonAsync不起作用

[英]PutAsJsonAsync does not work when dto has data annotations

我看到HttpClient和Web API與我的DTO有一些奇怪的行為。 當我為我的屬性准備好數據注釋時,HttpClient.PutAsJsonAsync()不起作用。 我無法在Web API端收到任何內容。 一些代碼解釋:

我的MVC 4網頁使用以下代碼調用Web API:

using (var client = new HttpClient())
{
    var response = client.PutAsJsonAsync(uri+"/"+MyObject.Id, MyObject).Result;
    response.EnsureSuccessStatusCode(); // Returns 500 when i use MyObject with annotations                             
}

要接收的Web API控制器代碼。 請注意,當MyObject具有注釋時,甚至不會觸發此操作:

public MyObject Put(MyObject myObject)
{
        try
        {
            if (myObject == null) throw new NullReferenceException();
        }
        catch (Exception e)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
        }
}

MyObject DTO工作時:

public class MyObject
{
    public int Id { get; set; }
    public Nullable<int> AuditProgramId { get; set; }
    public string Title { get; set; }
    public System.DateTime StartDate { get; set; }
    public System.DateTime EndDate { get; set; }
 }

MyObject DTO不起作用時:

public class MyObject
{
    public int Id { get; set; }
    public Nullable<int> AuditProgramId { get; set; }
    [Required]
    public string Title { get; set; }
    [Required, DataType(DataType.Date)]
    public System.DateTime StartDate { get; set; }
    [Required, DataType(DataType.Date)]
    public System.DateTime EndDate { get; set; }
 }

有任何想法嗎?

更新1

它可以在沒有注釋的情況下使用這些值,但是注釋失敗:

var myObj = new MyObject {
    Id=4,
    Title="Test Title",
    StartDate=DateTime.Today,
    EndDate=DateTime.Today.AddDays(2)
};

我可以重新編寫您的方案,並且異常消息實際上提供了此問題的解決方案:

Property 'StartDate' on type 'MvcApplication.Model.MyObject' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)].

我相應地修改了我的MyObject類,讓你的場景工作。

[DataContract]
public class MyObject
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public Nullable<int> AuditProgramId { get; set; }

    [DataMember]
    [Required]
    public string Title { get; set; }

    [Required, DataType(DataType.Date)]
    [DataMember(IsRequired = true)]
    public System.DateTime StartDate { get; set; }

    [Required, DataType(DataType.Date)]
    [DataMember(IsRequired = true)]
    public System.DateTime EndDate { get; set; }
}

僅供參考,最近修復了與此場景相關的錯誤,以簡化操作: 將[DataMember(IsRequired = true)]應用於具有值類型的必需屬性的過於激進的驗證

暫無
暫無

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

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