Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api 2 empty string parameter GET

i have setup the route to be: [Route("{id}/users/search/{search}")] and the associated action is: SomeAction(int id, string text)

The service has the following function. for the resource with id={id} and the users of this resource get the users that match with the {search} term (username, email etc).

the {search} can have a value so the service returns only the matching entities or does not have a value (empty string or null) so the service returns everything.

For the part with a value it works fine. For the second part i cannot find something to set the get request that matches the empty string.

i tried the following: 1/users/search/null {search} = "null" 1/users/search/ does not match route 1/users/search does not match route

has anyone a hint how this could be done?

Update: i have tried to replace the action: SomeAction(int id, string text) with: SomeAction(Model model) where model is

public class ApplicationUserSearchModel
{
    [Required]
    public int Id { get; set; }
    [Required(AllowEmptyStrings = true)]
    public string MatchText { get; set; }
}

with no luck since i don't know what to send in order to match the url to this.

like image 749
Mantzas Avatar asked Feb 22 '15 18:02

Mantzas


1 Answers

You should tag your search parameter with ? to mark it as optional in the route, and set it to null by default in your action.

[Route("{id}/users/search/{search?}")]
public HttpResponseMessage Search(int id, string search = null)    

I originally thought the route/action parameter names were the issue, but I was incorrect. Here is the previous answer:

The parameter names in your route definition and your action don't match, which is causing your problem.

[Route("{id}/users/search/{search}")]
public HttpResponseMessage Search(int id, string text)

You should update the string parameter in your action from text to search, to match the parameter name in your Route attribute.

like image 139
matthughes404 Avatar answered Oct 21 '22 05:10

matthughes404