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

◇◆丶佛笑我妖孽 提交于 2020-01-11 07:41:08

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/25077406/regex-in-route-attribute-restful-api-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!