2014-11-03 54 views
0

目前,我有以下爲每個實體/資源提供分頁的一組API的方式:分頁中的WebAPI

public IHttpActionResult GetPageUsers(int startindex, int size, string sortby = "Username", string order = "DESC") 
{ 
    if (!order.Equals("ASC") && !order.Equals("DESC")) 
     return BadRequest("Order Has To Be DESC or ASC"); 

    if (!new string[] { "username", "name" }.Contains(sortby.ToLower())) 
     return BadRequest("Not A Valid Sorting Column"); 

    return Ok(new 
    { 
     records = Mapper.Map<List<User>, List<HomeBook.API.Models.User.UserDTO>>(
      db.Users.OrderBy(sortby + " " + order).Skip(startindex).Take(size).ToList() 
     ), 
     total = db.Users.Count() 
    }); 
} 

但我想移動的驗證邏輯模型,以便我能回信ModelState來自我的一個Action過濾器的錯誤和請求甚至不需要進入控制器。

但我不能改變動作簽名期望一個對象參數到我已經在其他地方,我得到multiple action error

基本上,我問的是如何從這裏刪除驗證邏輯到其他地方,以便請求甚至不需要進入操作內部。我真的很感激一般

回答

1

在這個問題上的一些見解,甚至分頁中WebAPIs你可以定義操作過濾器屬性來進行驗證:

public class ValidatePagingAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     string order = (string) actionContext.ActionArguments["order"]; 
     string sortBy = (string) actionContext.ActionArguments["sortby"]; 

     var states = new ModelStateDictionary(); 
     if(!order.Equals("ASC") && !order.Equals("DESC")) 
     { 
      states.AddModelError("order", "Order has to be DESC or ASC"); 
     } 

     if (!new[] { "username", "name" }.Contains(sortBy.ToLower())) 
     { 
      states.AddModelError("sortby", "Not A Valid Sorting Column"); 
     } 

     if(states.Any()) 
     { 
      actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, states); 
     } 
    } 
} 

,然後用它像這樣:

[ValidatePaging] 
public IHttpActionResult GetPageUsers(int startindex, int size, string sortby = "Username", string order = "DESC") 
{ 
    // stuff 
} 

另外,請看http://bitoftech.net/2013/11/25/implement-resources-pagination-asp-net-web-api關於如何在web api中實現分頁。