Route属性中的正则表达式 – RESTful API ASP.NET Web API
我在Route属性中遇到了正则表达式的问题。 我想创建RESTful API,您可以在其中指定URL中的开始日期和结束日期以过滤结果。 我到现在所做的是:
[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 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) r.LastModified) .ToList(); return output; }
它不是我想要的,因为第二个参数应该是可空的。 当我只通过开始日期时,我得到404.使用斜杠格式也不起作用。 我究竟做错了什么? 我以为*意味着参数可以为空…
===编辑===
我要匹配的url都是:
https:// localhost:post / api / recommendations / date / 10/07/2013 / 1/08 / 2014 – 不起作用
https:// localhost:post / api / recommendations / date / 10-07-2013 / 1-08-2014 – 有效
并且可以为第二个参数:
https:// localhost:post / api / recommendations / date / 10/07/2013 – 不起作用
https:// localhost:post / api / recommendations / date / 10-07-2013 – 不起作用
对于可为空的第二个参数,请将路径模板写为
[Route("api/recommendations/date/{startDate:datetime:regex(\\d{2}-\\d{2}-\\d{4})}/{endDate:datetime:regex(\\d{2}-\\d{2}-\\d{4})?}")]
您应该为可空参数提供默认值
public IEnumerable GetRecommendationByDate(DateTime startDate, DateTime? endDate = null)
对于斜杠,斜杠用于分隔url段,这意味着除非编码,否则单个段不能包含斜杠。