Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

c# - Multiple Optional Parameters with ServiceStack.Net

I'm trying to implement a service with Multiple Optional Parameters using ServiceStack.Net

At the moment my route looks like this

Routes.Add<SaveWeek>("/save/{Year}/{Week}");

I want to support uris like this:

/save/2010/12/Monday/4/Tuesday/6/Wednesday/7

ie Monday=4, Tuesday=6 and Wednesday=7

However I want the ability to ignore days i.e. the person calling the service can decide if they want to save each value for each day...

i.e. Like this with missing parameter values

?Monday=4&Wednesday=7&Friday=6

Of course one solution would be to have the following route and just pass 0 when I don't want to save the value.

Routes.Add<SaveWeek>("/save/{Year}/{Week}/{Monday}/{Tuesday}}/{Weds}/{Thurs}/{Fri}/{Sat}/{Sun}");

But..... is there a better way of achieving this functionality?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When your Route requirements start to get too complicated it will eventually become easier just to add a wild card path so you can parse the rest of the querystring yourself. i.e. in this case since the first part of the querystring remains constant you can add a wild card mapping to store the variable parts of the querystring, i.e:

Routes.Add("/save/{Year}/{Week}/{DaysString*}");

ServiceStack will still populate the partial DTO with the Year and Week fields (as well any fields that were passed in the querystring). The remaining variable parts of the url is stored in the DaysString which you are then free to parse yourself manually. So the above mapping will be able to match urls like:

/save/2010/12/Monday/4/Tuesday/6?Wednesday=7

And populate the following variables in your Request DTO:

  • Year: 2010
  • Week: 12
  • Wednesday: 7
  • DaysString: Monday/4/Tuesday/6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...