c# - 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
解决方案
也许这两个线程有不同的文化?
尝试指定日期时间格式:
var result = DateTimeOffset.TryParse(
"Sun, 07 Mar 2021 11:31:14 GMT",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.None,
out var date);
或使用DateTimeOffset.TryParseExact
.
推荐阅读
- java - 如何将具有偏移时间(+05:30)的日期时间解析为 LocalDateTime
- amazon-web-services - Redshift:无效操作:超过允许的最大存储过程数
- python - 从数据框中的列表中删除字符串
- java - 比较两个 HashMap 并将映射值相乘
- javascript - 如何在每次页面加载时停止执行 JavaScript 代码
- php - 从列表php中删除项目的最佳方法
- flutter - 在 Play 商店中将 Flutter 应用程序从旧版本更新到新版本
- amazon-web-services - 有没有办法将 EBS 快照复制到其他地区的另一个账户?(跨地域、跨账号)
- laravel - 如何在laravel中制作两个If条件
- javascript - 功能:调用 JSON 数据的 API,显示所需参数的速率 --> IMPORTJSON(url,xpath) ex。IMPORTJSON(x.com, rates.f) --> 0.042