0

I've got a problem with regular expressions in Route attribute. I'd like to create RESTful API, where you can specify start date and end date in URL to filter results. What I've done till now is:

    [HttpGet]
    [Route("date/{startDate:datetime:regex(\\d{4}-\\d{2}-\\d{2})}/{*endDate:datetime:regex(\\d{4}-\\d{2}-\\d{2})}")]
    [Route("date/{startDate:datetime:regex(\\d{4}/\\d{2}/\\d{2})}/{*endDate:datetime:regex(\\d{4}/\\d{2}/\\d{2})}")]
    public IEnumerable<Recommendation> GetRecommendationByDate(DateTime startDate, DateTime? endDate) 
    {
        var output = db.Recommendations
            .Where(r => r.IsPublished == true &&
                        r.CreatedDate.CompareTo(startDate) > 0 &&
                        r.CreatedDate.CompareTo(endDate.HasValue ? endDate.Value : DateTime.Now) < 0)
            .OrderByDescending(r => r.LastModified)
            .ToList();

        return output;
    }

It doesn't work how I want, because second param should be nullable. When I pass only start date, I'm getting 404. Also format with slash doesn't work at all. What am I doing wrong? I thought * means that parameter is nullable...

===EDIT===

My URLs to match are both:

https:// localhost:post/api/recommendations/date/10/07/2013/1/08/2014 - doesn't work

https:// localhost:post/api/recommendations/date/10-07-2013/1-08-2014 - works

and with nullable second parameter:

https:// localhost:post/api/recommendations/date/10/07/2013 - doesn't work

https:// localhost:post/api/recommendations/date/10-07-2013 - doesn't work

5
  • What is your url to match? Commented Aug 4, 2014 at 3:43
  • I've just edited the post to show you URL-s. Commented Aug 4, 2014 at 8:25
  • Do your urls with startDate and endDate work fine? Commented Aug 4, 2014 at 8:58
  • Yes, works fine in the format with dashes. It doesn't work with null second parameter and with slashes. As I marked in edited post. Commented Aug 4, 2014 at 10:44
  • 1-08-2014 is invalid? because "1" only has one digit. And the format should be 2-2-4 instead of 4-2-2 Commented Aug 5, 2014 at 4:52

1 Answer 1

4

For nullable second parameter, write your route template as

[Route("api/recommendations/date/{startDate:datetime:regex(\\d{2}-\\d{2}-\\d{4})}/{endDate:datetime:regex(\\d{2}-\\d{2}-\\d{4})?}")]

And you should provide with a default value for nullable parameter

public IEnumerable<Recommendation> GetRecommendationByDate(DateTime startDate, DateTime? endDate = null)

For slashes, slash is used to separate url segments, which means one single segment can't contain slash unless they are encoded.

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

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.