问题
Currently I have following way of providing pagination for every entity/resource for a set of APIs:
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()
});
}
But I would like to move the validation logic to Model so that I can reply back with ModelState
errors from one of my Action filters and the request would not even need to get inside the controller.
But I cannot also change the action signature to expect an object parameter to what I have already otherwise, I get multiple action error
.
Basically, what I am asking is how I can remove validation logic from here to somewhere else so that the request does not even need to get inside the action. I would really appreciate some insight on this problem or even pagination in WebAPIs in general
回答1:
You could define an action filter attribute to perform the validation:
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);
}
}
}
And then use it like so:
[ValidatePaging]
public IHttpActionResult GetPageUsers(int startindex, int size, string sortby = "Username", string order = "DESC")
{
// stuff
}
Also, have a look at http://bitoftech.net/2013/11/25/implement-resources-pagination-asp-net-web-api on how to implement paging in web api.
来源:https://stackoverflow.com/questions/26711756/pagination-in-webapi