ASP.net Core 6 - 如何将序列化日期转换为DateTime?

ASP.net Core 6 - How to convert serialized dates into DateTime?

在我的控制器中,我有一个需要输入两个日期的 httpget(理想情况下没有时间,但无论哪种方式都应该有效)。

 // GET: api/Shippingschedules/shipname
        [HttpGet("{startdate},{enddate}")]
        public async Task<ActionResult<Shippingschedule>> GetShippingSchedulesByDates(string startdate, string enddate)
        {
            CultureInfo ukCulture = new CultureInfo("en-GB");
            DateTime sDate = DateTime.Parse(startdate, ukCulture.DateTimeFormat);
            DateTime eDate = DateTime.Parse(enddate, ukCulture.DateTimeFormat);

            ActionResult<Shippingschedule> Shippingschedule = await _context.Shippingschedules.Where(
                x => x.StartDate >= sDate && x.EndDate <= eDate).FirstOrDefaultAsync();

            if (Shippingschedule == null)
            {
                return NotFound();
            }

            return Shippingschedule;
        }

当我调试到 sDate 行时,程序停止并出现错误:

String '1%2F1%2F2022' was not recognized as a valid DateTime. at System.DateTime.Parse(String s, IFormatProvider provider)

如何将其反序列化为真正的 datetime 对象?

谢谢

试试这个

using System.Net;

 var startdateDecoded= WebUtility.UrlDecode(startdate);
var enddateDecoded= WebUtility.UrlDecode(enddate);

CultureInfo ukCulture = new CultureInfo("en-GB");
 DateTime sDate = DateTime.Parse(startdateDecoded, ukCulture.DateTimeFormat);

.....