简体   繁体   中英

REST API Optional parameters

I build a Web Role with rest api. All its arguments should be optional with default values

I tried this:

  [WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/param2/{param2}/param3/{param3}")]
    public string RetrieveInformation(string param1, string param2, string param3)
    {

    }

I want that it will work for the following scenarios:

https://127.0.0.1/RetrieveInformation/param1/2  

https://127.0.0.1/RetrieveInformation/param1/2/param3/3 

How can I do that?Will the below work?

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1=1}/param2/{param2=2}/param3/{param3=3}")]

I don't think that you can achieve this when using segments (ie using /). You could use a wildcard character but it only allows you to do so for the last segment.

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/{*param2}")]

If you don't really need segments and can use query parameters, the following route will work

[WebGet(UriTemplate = "RetrieveInformation?param1={param1}&param2={param2}&param3={param3}")]

Such a route will give you flexibility as parameters do not need to be ordered, nor are required. This will work with the following

http://localhost:62386/Service1.svc/GetData?param1=1&param2=2&param3=3
http://localhost:62386/Service1.svc/GetData?param1=1&param3=3&param2=2
http://localhost:62386/Service1.svc/GetData?param1=1&param2=2
http://localhost:62386/Service1.svc/GetData?param1=1&param3=3

You can find more information about UriTemplate @ http://msdn.microsoft.com/en-us/library/bb675245.aspx

Hope this helps

The param1 may not be optional when a param2 is defined, so doing this in a single route might be a bit cumbersome (if even possible). It might be better to split your GET into multiple routes.

Something like the below code might work better for you...

[WebGet(UriTemplate = "RetrieveInformation")]
public string Get1()
{
    return RetrieveInfo(1,2,3);
}

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}")]
public string GetP1(int param1)
{
    return RetrieveInfo(param1,2,3);
}

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/param2/{param2}")]
public string GetP1P2(int param1, int param2)
{
    return RetrieveInfo(param1,param2,3);
}

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/param3/{param3}")]
public string GetP1P3(int param1, int param3)
{
    return RetrieveInfo(param1,2,param3);
}

private string RetrieveInfo(int p1, int p2, int p3)
{
    ...
}

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