2016-02-18 76 views
2

我得到的參數在我的web API操作使用[FromUri],例如:獲取參數使用FromUri和驗證此參數

public TestController 
{ 
    public ActionResult TestMethod([FromUri] int testParamFromUri) 
    { 
     //here is my validation 
     if(testParamFromUri < 1 || testParamFromUri > 50) 
     { 
      throw new TestException(); 
     } 

     //other code 
    } 
} 

我只是需要驗證輸入參數的使用屬性,並拋出新的異常,如果參數不沒有用。 我嘗試使用範圍屬性,像這樣:

public ActionResult TestMethod([FromUri] [Range(1,50,"Error message")] int testParamFromUri) 

但這種方式並不爲我工作。 請告訴我我錯在哪裏,或告訴我我應該怎麼做驗證輸入參數。

p.s.我需要輸入參數使用[FromUri]屬性並驗證此參數使用其他屬性。

+0

DataAnnotations.Range在類屬性中使用,而不是在方法參數。您可以在TestMethod中使用if語句進行驗證。 –

+0

@RicardoPontual我認爲我可以創建驗證輸入參數的屬性,或者這是不可能的? – netwer

+0

你可以,但它更容易驗證方法或簡單的passa類作爲參數,所以你可以在類中使用DataAnnotations。像這樣:public class Param {[Range(1,50,ErrorMessage =「Error Message」)] public int testParamFromUri {get;組; }}和公共IHttpActionResult TestMethod([FromUri] Param testParamFromUri) –

回答

1

可以創建一個Input模型與testParamFromUri屬性和使用Range屬性驗證它:

public class TestController : ApiController 
{ 
    public IHttpActionResult TestMethod([FromUri]Input input) 
    { 
     if (!ModelState.IsValid) 
      return BadRequest(ModelState); 

     //other code 

     return Ok(); 
    } 
} 

public class Input 
{ 
    [Range(1, 50, ErrorMessage = "Error Message")] 
    public int testParamFromUri { get; set; } 
} 
+0

謝謝你的回答,是的,我知道。但是我需要使用不像模型的參數 – netwer

+0

@netwer可以使用此模型發出類似'http:// server/api/Test/54'的請求。是否有任何其他限制不允許您使用該模型? –

+0

我的請求是:https:// domain/api/data?testparam1 = 30&testparam2 = 60等。我需要類似可重用屬性的輸入參數,因爲爲其他我的api方法創建模型我認爲不好。附:其他方法有一個或兩個輸入參數 – netwer