How should I pass multiple parameters to an ASP.Net Web API GET?
I think the easiest way is to simply use AttributeRouting
.
It's obvious within your controller, why would you want this in your Global WebApiConfig
file?
Example:
[Route("api/YOURCONTROLLER/{paramOne}/{paramTwo}")] public string Get(int paramOne, int paramTwo) { return "The [Route] with multiple params worked"; }
The {}
names need to match your parameters.
Simple as that, now you have a separate GET
that handles multiple params in this instance.
Just add a new route to the WebApiConfig
entries.
For instance, to call:
public IEnumerable<SampleObject> Get(int pageNumber, int pageSize) { ..
add:
config.Routes.MapHttpRoute( name: "GetPagedData", routeTemplate: "api/{controller}/{pageNumber}/{pageSize}");
Then add the parameters to the HTTP call:
GET //<service address>/Api/Data/2/10
I just had to implement a RESTfull api where I need to pass parameters. I did this by passing the parameters in the query string in the same style as described by Mark's first example "api/controller?start=date1&end=date2"
In the controller I used a tip from URL split in C#?
// uri: /api/coursespublic IEnumerable<Course> Get(){ NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query); var system = nvc["System"]; // BL comes here return _courses;}
In my case I was calling the WebApi via Ajax looking like:
$.ajax({ url: '/api/DbMetaData', type: 'GET', data: { system : 'My System', searchString: '123' }, dataType: 'json', success: function (data) { $.each(data, function (index, v) { alert(index + ': ' + v.name); }); }, statusCode: { 404: function () { alert('Failed'); } } });
I hope this helps...