Passing DateTimeOffset as WebAPI query string

前端 未结 8 628
感动是毒
感动是毒 2020-12-11 15:49

I\'ve got a WebAPI action that looks like so:

[Route(\"api/values/{id}\")]
public async Task Delete(string id, DateTimeOffset date         


        
8条回答
  •  星月不相逢
    2020-12-11 16:42

    Best way to find out is to ask the WebAPI to generate the expected URL format itself:

    public class OffsetController : ApiController
    {
        [Route("offset", Name = "Offset")]
        public IHttpActionResult Get(System.DateTimeOffset date)
        {
            return this.Ok("Received: " + date);
        }
    
        [Route("offset", Name = "Default")]
        public IHttpActionResult Get()
        {
            var routeValues = new { date = System.DateTimeOffset.Now };
            return this.RedirectToRoute("Offset", routeValues);
        }
    }
    

    When a call to /offset is made the response will return a 302 to a url that contains the 'date' parameter in the querystring. It will look something like this:

    http://localhost:54955/offset?date=02/17/2015 09:25:38 +11:00

    I could not find an overload of DateTimeOffset.ToString() that would generate a string value in that format except for explicitly defining the format in a string format:

    DateTimeOffset.Now.ToString("dd/MM/yyyy HH:mm:ss zzz")
    

    Hope that helps.

提交回复
热议问题