Reputation: 5446
I have this web api controller that extending the Linq Dynamic to do ApplySort via a string
I could pass several sortby i.e: sort=id,name,datecreated into this web api. The challenge though I need to validate these strings (Id, Name, DateCreated etc etc) exist in the model/class's property before doing the Linq stuff. How do I do that?
[HttpGet]
[Route("api/Activities/{sort=id}/{pagenumber=1}/{pagesize=10}")]
[CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
public async Task<IHttpActionResult> GetActivities(string sort, int pageNumber, int pageSize)
{
string userId = User.Identity.GetUserId();
var activities = await (db.Activities.Where(q => q.UserId == userId)
.AsQueryable().ApplySort(sort)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)).ToListAsync();
return Ok(activities);
}
Upvotes: 0
Views: 48
Reputation: 1869
You could use GetProperties():
[HttpGet]
[Route("api/Activities/{sort=id}/{pagenumber=1}/{pagesize=10}")]
[CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
public async Task<IHttpActionResult> GetActivities(string sort, int pageNumber, int pageSize)
{
string userId = User.Identity.GetUserId();
var propertyNames = typeof (Activity).GetProperties().Select(p=>p.Name).ToList();
var sorts = sort.Split(',').Select(s=> s.Trim());
foreach(var sortPart in sorts)
{
if(propertyNames.IndexOf(sortPart)<0)
{
throw//what ever should be done in error-case
}
}
var activities = await (db.Activities.Where(q => q.UserId == userId)
.AsQueryable().ApplySort(sort)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)).ToListAsync();
return Ok(activities);
}
Upvotes: 1