Web Api 2 empty GET string parameter

I set the route as follows: [Route ("{ID} / users / search / {Search}")] and the action associated with it: SomeAction (int id, string text)

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

{search} may matter, therefore the service returns only the relevant objects or does not matter (empty string or null), therefore the service returns everything.

For the value part, it works great. For the second part, I cannot find something to set a get request that matches an empty string.

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

there is a hint how can this be done?

Update: I tried replacing the action: SomeAction (int id, string text) with: SomeAction (model model), where the model

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

no luck since I don't know what to send to match the url.

+5
source share
1 answer

Should you tag your search parameter ? to mark it as optional on the route, and by default set it to null in its action.

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

Initially, I thought the route / action parameter names were a problem, but I was incorrect. Here is the previous answer:

The parameter names in the route definition and actions do not match, which causes problems.

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

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

+4
source

Source: https://habr.com/ru/post/1213926/


All Articles