2017-09-20 62 views
0

我有一個Web API應用程序,我有一個HTTP POST動作以DTO如下:如何在web api中動作參數的類型不匹配時返回404?

public class Account 
{ 
    public string Name { get; set; } 

    public string Email { get; set; } 

    public int Age { get; set; } 
} 

但使用郵差,我可以將它傳遞這樣的:

{ 「名稱」:「簡單代碼「,電子郵件:」[email protected]「,年齡:空}

當我發送請求時,它將Age發送爲空。

如何讓我的web api返回404而不發送請求,或者我是否強制驗證我的代碼?

回答

0

喜對我來說最快捷的方法是:

標記爲[必填]您的DTO

public class Account 
{ 
    public string Name { get; set; } 

    [Required(AllowEmptyString = false)] 
    public string Email { get; set; } 

    [Required] 
    public int Age { get; set; } 
} 

然後在您的API方法

public IHttpActionResult Post([FromBody] mydto){ 

    // if model is not validated return 400 bad request 
    if(!ModelState.IsValid) return BadRequest(ModelState); 

    //or if is here it's ok 

    //return 200 OK 
    Ok(mydto); 
} 
+0

你試圖公衆詮釋?年齡{get;組; } –

+0

你有沒有試過public int?年齡{get;組; } –

相關問題