简体   繁体   中英

How to pass optional parameters in Web API

Can you please help me to pass optional parameters in between in a uri

[Route("api/values/{a}/{b?}/{c?}")]
public string Get(string a = "", string b = "", string c = "")
{
    return string.Format("a={0}, b={1}, c={2}", a, b, c);
}

I can call the api -

api/values/abc/pqr/xyz returns a=abc, b=pqr, c=xyz
api/values/abc/pqr returns a=abc, b=pqr, c=

But i would like to call the api like -

api/values/abc//xyz which should return a=abc, b=, c=xyz
returns a=abc, b=xyz, c=

Can anyone help

That's the way URI's are meant to be - they should represent certain path to the object. You should not be able to get to "c" without specifying "b" or "a" on the way.

But if you really want to, maybe just use some kind of wildcard as value? For example: /api/values/abc/*/xyz and in your code just check if part of path is your wildcard. That way you'll expand logic of URI's rather then breaking it. URI will remain human-readable and obvious (eg. get all values XYZ that are somewhat descendant of container ABC).

To keep things DRY write a custom model binder that will convert any wildcard found in URL to a null (or other) value that will then be passed to your controller. Take a look at System.Web.Http.ModelBinding namespace to get you started.

A simple workaround would be to just use optional query parameters:

    [Route("api/values")]
    public string Get(string a = "", string b = "", string c = "")
    {
        return string.Format("a={0}, b={1}, c={2}", a, b, c);
    }

=>

/api/values?a=abc&c=xyz

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