简体   繁体   中英

DateTimeOffset TryParse not accepting valid datetime - C# OWIN implementation

I'm using C# OWIN framework for authentication and I have the TokenEndpoint override method which converts IssuedDate & ExpiresDate in the proper format, so I have used DateTimeOffset.TryParse method to check and return datetime, so now the issue that I 'm facing is really strange, one of the service works properly that returns true for the method DateTimeOffset.TryParse while the other service returns false even though both are passing the same date format. Earlier I used DateTimeOffset.Parse and it failed with the reason 'string was not recognized as a valid datetime.' so I changed to DateTimeOffset.TryParse to handle error but I 'm still not able to find the root cause.

 public override async Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (System.Collections.Generic.KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                DateTimeOffset result;
                if ((property.Key.Equals(".issued") || property.Key.Equals(".expires")) && DateTimeOffset.TryParse(property.Value, out result))
                {
                    context.AdditionalResponseParameters.Add(property.Key, result.UtcDateTime.ToString("yyyy/MM/dd HH:mm:ss"));
                }
                else
                {
                    context.AdditionalResponseParameters.Add(property.Key, property.Value);
                }
            }
        }

Both the services passes date in the below format. Sun, 07 Mar 2021 11:31:14 GMT Sun, 07 Mar 2021 11:32:44 GMT

Please check the snapshot在此处输入图像描述

Maybe the two threads have different Cultures ?

Try to specify the date time format:

var result = DateTimeOffset.TryParse(
                "Sun, 07 Mar 2021 11:31:14 GMT", 
                CultureInfo.InvariantCulture.DateTimeFormat,
                DateTimeStyles.None,
                out var date);

Or use DateTimeOffset.TryParseExact .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM