Reputation: 10153
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}")]
Upvotes: 1
Views: 3682
Reputation: 3236
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)
{
...
}
Upvotes: 1
Reputation: 2629
I don't think that you can achieve this when using segments (i.e. 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}¶m2={param2}¶m3={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¶m2=2¶m3=3
http://localhost:62386/Service1.svc/GetData?param1=1¶m3=3¶m2=2
http://localhost:62386/Service1.svc/GetData?param1=1¶m2=2
http://localhost:62386/Service1.svc/GetData?param1=1¶m3=3
You can find more information about UriTemplate @ http://msdn.microsoft.com/en-us/library/bb675245.aspx
Hope this helps
Upvotes: 3