简体   繁体   中英

WebAPI routing to a function with multiple optional parameters

I have the following function header in WebAPI controller declared as route:

[Route("page/{page}/{cityfilter?}/{statefilter?}/{organizationfilter?}")]
public IEnumerable<Contact> GetContact(int page, string cityfilter = null, string statefilter = null, string organizationfilter = null)
{
     ...
}

The issue here is that I'd wish that every parameter is optional, so I'd want to make a request that has either a cityfilter, a statefilter, an organization filter, two of them or three of them, and then be processed and router by this function, but I have no clue about how I can build the URI so that, for instance, this route works for just the statefilter.

How can I do that in WebAPI? How should I call the resource address from, for instance, a Jquery Ajax call?

Thank you.

Since the parameters are simple types (strings), they can be bound either from the route data (URL path) or the query string. So you can move the optional parameters to the query string and have your route only match the page parameter.

[Route("page/{page}")]

Here's an example of a URL that you would use to call this action from the browser or from an AJAX call:

www.yourapidomain.com/page/1?cityfilter=aCityFilterString&statefilter=aStateFilterString&organizationfilter=anOrganizationFilter

You may of course omit any of the optional parameters or change their order.

The action method signature can remain as it is in your example.

For more information, you can have a look at parameter binding ASP.NET Web API .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM