Reputation: 1701
What is the best approach to reuse the type and name of common resource parameters within an ASP.NET Web API project? Some examples:
public HttpResponseMessage GetObjects(int rpp, int page, string q, string include)
{
...
}
Could be implemented as:
public HttpResponseMessage GetObjects([FromUri] CustomParameterModel)
{
...
}
public CustomParameterModel
{
// results per page
public int rpp { get; set; }
// current page
public int page { get; set; }
// search terms
public string q { get; set; }
// include defined properties
public string include { get; set; }
}
Both approaches described above results in the following URL: objects?rpp={rpp}&page={page}&q={q}&include={include}
This is fine for the objects resource, but not for the files resource for example. The files resource does not need the include parameter.
public HttpResponseMessage GetFiles(int rpp, int page, string q)
{
...
}
How could this be achieved in an elegant way without rewriting the type and name of the parameters?
Upvotes: 0
Views: 407
Reputation: 21
I think you could write own model binder (http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api) which will serve that for you.
Another approach would be to write message handler which could pre process requests (http://www.asp.net/web-api/overview/working-with-http/http-message-handlers) and validate your parameters (assign default values etc).
Finally, if you do not mark fields as required (http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api) they could leave with default values, for yours that could be 0 for int or null for int? and null for string.
It is always about the particular case, try different approaches and find best which fits to your needs.
Upvotes: 1