【问题标题】:DateTime User Claim, format date as string (Asp.Net MVC 5)DateTime 用户声明,将日期格式化为字符串(Asp.Net MVC 5)
【发布时间】:2020-05-09 00:25:00
【问题描述】:

尝试在我的 IdentityModels 文件中将 DateOfBirth 类型的声明添加到我的 userIdentity。

public class ApplicationUser : IdentityUser
{
    public ICollection<Pet> Pets { get; set; }
    public System.DateTime DateofBirth { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim(ClaimTypes.DateOfBirth, this.DateofBirth));


        return userIdentity;
    }


}

代码CS1503的2个错误:

Argument1:无法从“字符串”转换为“System.IO.BinaryReader” Argument2:cannon 从 'System.DateTime' 转换为 'System.Security.Claims.ClaimsIdentity'

很明显我有类型错误,但我只是不知道如何将我的 DateTime 转换为字符串。

谢谢

【问题讨论】:

  • DateOfBirth.ToString("yyyy-MM-dd")

标签: c# .net asp.net-mvc asp.net-mvc-5


【解决方案1】:

在 .NET 中有多种标准方法可以将日期时间格式化为字符串。

  1. 使用预先指定的格式(例如,DateOfBirth.ToString("s") 用于可排序格式(来源:.net docs)
  2. 指定自定义格式(即DateOfBirth.ToString("yyyy-MM-dd hh:mm:ss")(来源:.NET DateTime to String)。您可以按预期取出片段并更改分隔符/周围文本,但也有格式说明符用于缩短格式和更小的时间单位。李>

为了将来参考,这个问题的一个更好的标题可能是“C#:如何将日期时间转换为字符串”或另一个标题,它传达了让你卡住的部分。然后,您将获得更多了解您问题的人的意见。

【讨论】:

    【解决方案2】:

    根据方法的定义,它的说法需要添加为字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多