Passing DateTimeOffset as WebAPI query string

前端 未结 8 596
感动是毒
感动是毒 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:33

    Here is the easiest way for those who are looking for some kind of sync between client and server using datetime. I implemented that for mobile application. It is independent from the culture of the client. because my mobile app supports multiple cultures and it is boring to use formatting between those cultures. thanks that .net has a perfect functions called ToFileTime and FromFileTime

    Server Controller Action:

    [HttpGet("PullAsync")]
    public async Task<IActionResult> PullSync(long? since = null, int? page = null, int? count = null)
    {
        if (since.HasValue) 
            DateTimeOffset date = DateTimeOffset.FromFileTime(since.Value);    
    }
    

    Client Side

    DateTimeOffset dateTime = DateTime.Now.ToFileTime();
    var url= $"/PullAsync?since={datetime}&page={pageno}&count=10";
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题