Reputation: 491
I have a GET() controller to retrieve a list of entities. I want to pass a parameter to the action to filter the list of objects returned as follows:
Mysite.com/Users?nameContains=john
This is my action definition:
public IEnumerable<object> Get(string nameContains)
{
// I want to use nameContains here
}
I get an error:
The requested resource does not support http method 'GET'.
If I revert the method to not get that parameter, it works.
Upvotes: 1
Views: 1783
Reputation: 491
Sorry, it was my mistake, I used 2 parameters and I didn't pass one of them (nor assigned it a default value) so it returned an error. Cheers.
Upvotes: 1
Reputation: 103305
You can add a new route to the WebApiConfig
entries.
For instance, your method definition:
public IEnumerable<object> Get(string nameContains)
{
// I want to use nameContains here
}
add:
config.Routes.MapHttpRoute(
name: "GetSampleObject",
routeTemplate: "api/{controller}/{nameContains}"
);
Then add the parameters to the HTTP call:
GET //<service address>/Api/Data/test
or use HttpUtility.ParseQueryString in your method
// uri: /Api/Data/test
public IEnumerable<object> Get()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
var contains = nvc["nameContains"];
// BL with nameContains here
}
Upvotes: 0
Reputation: 9804
Try this
public IEnumerable<object> Get([FromUri] string nameContains)
{
// I want to use nameContains here
}
Also since you are working in Web Api 2, you can make use of attribute routing
[Route("users")]
public IEnumerable<object> Get([FromUri] string nameContains)
{
Upvotes: 1