2

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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.