我得到的參數在我的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]
屬性並驗證此參數使用其他屬性。
DataAnnotations.Range在類屬性中使用,而不是在方法參數。您可以在TestMethod中使用if語句進行驗證。 –
@RicardoPontual我認爲我可以創建驗證輸入參數的屬性,或者這是不可能的? – netwer
你可以,但它更容易驗證方法或簡單的passa類作爲參數,所以你可以在類中使用DataAnnotations。像這樣:public class Param {[Range(1,50,ErrorMessage =「Error Message」)] public int testParamFromUri {get;組; }}和公共IHttpActionResult TestMethod([FromUri] Param testParamFromUri) –