简体   繁体   中英

Regex in Route attribute - RESTful API ASP.NET Web API

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

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.

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