1

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.

9
  • Try to send as body object. You can get then Commented Feb 18, 2014 at 12:18
  • How you define your route? Commented Feb 18, 2014 at 12:18
  • @AmitAgrawal I'd rather not to because it wouldn't be compliant to the RESTful API best practices. @ssilas777 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); Commented Feb 18, 2014 at 12:20
  • @NadavMiller Best practise in Web Api send parameter as body or define in URL and map that in registerRoute Commented Feb 18, 2014 at 12:21
  • 1
    @AmitAgrawal Where did you get that "best practice" advice because I've never heard of it before? Commented Feb 18, 2014 at 12:24

3 Answers 3

1

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)
{
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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
}

1 Comment

There should be no need to do this. Query parameter mapping does work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.