ASP.NET Core:AccessToken未实现接口成员的报错解决方法
解决ASP.NET Core 6中接口实现的报错问题
报错原因很明确:C#规定,类实现接口时必须实现接口中定义的所有成员。你的AccessToken类声明了实现IEntity和IAuditable,但没有添加这两个接口要求的所有属性,因此编译器抛出未实现接口成员的错误。
下面提供两种解决方案:
方法1:直接在AccessToken类中实现所有接口成员
直接把两个接口定义的属性添加到AccessToken类中,完整代码如下:
public class AccessToken : IEntity, IAuditable { // 实现IEntity接口的成员 public Guid Id { get; set; } // 实现IAuditable接口的成员 public Guid CreatedBy { get; set; } public DateTimeOffset? CreatedOn { get; set; } public DateTimeOffset? LastModifiedOn { get; set; } public Guid? LastModifiedBy { get; set; } public bool? IsDeleted { get; set; } public DateTimeOffset? DeletedOn { get; set; } public Guid? DeletedBy { get; set; } // AccessToken自身的属性 public string IssuedBy { get; set; } public string Audience { get; set; } public string IpAddress { get; set; } public string UserAgent { get; set; } public string Header { get; set; } public string Subject { get; set; } public string TokenId { get; set; } public Guid? ApplicationId { get; set; } public Guid LoginId { get; set; } public string ClientToken { get; set; } public string Claims { get; set; } }
方法2:创建抽象基类复用接口实现
如果项目中有多个实体需要实现IEntity和IAuditable,推荐用抽象基类统一实现这些属性,避免重复代码:
首先定义抽象基类:
public abstract class BaseEntity : IEntity, IAuditable { public Guid Id { get; set; } public Guid CreatedBy { get; set; } public DateTimeOffset? CreatedOn { get; set; } public DateTimeOffset? LastModifiedOn { get; set; } public Guid? LastModifiedBy { get; set; } public bool? IsDeleted { get; set; } public DateTimeOffset? DeletedOn { get; set; } public Guid? DeletedBy { get; set; } }
然后让AccessToken继承这个基类即可:
public class AccessToken : BaseEntity { public string IssuedBy { get; set; } public string Audience { get; set; } public string IpAddress { get; set; } public string UserAgent { get; set; } public string Header { get; set; } public string Subject { get; set; } public string TokenId { get; set; } public Guid? ApplicationId { get; set; } public Guid LoginId { get; set; } public string ClientToken { get; set; } public string Claims { get; set; } }
这种方式既解决了报错,还能让其他实体直接复用基类的接口实现,提升代码可维护性。
内容的提问来源于stack exchange,提问作者Gbenga
相关产品推荐
相关产品推荐

