首页 > 解决方案 > 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 snapshotenter image description here

标签: c#owindatetimeoffsettryparse

解决方案


也许这两个线程有​​不同的文化

尝试指定日期时间格式:

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

或使用DateTimeOffset.TryParseExact.


推荐阅读