【发布时间】:2015-11-14 02:57:49
【问题描述】:
我有一个 ASP.NET Web API 应用程序,它有两种类型的用户——客户端和驱动程序。目前,我在客户端和驱动程序控制器中有用于注册客户端和驱动程序的方法。我意识到做到这一点的正确方法是通过ApplicationUser 类的内置身份验证系统。基本上,整个事情让我感到困惑,因为对于两种用户类型,我都有不同的字段。无论如何,我已经提出了两种可能的解决方案,但是,它们听起来都不是实现目标的正确方法。
1) 继承自ApplicationUser
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
[Column(TypeName = "datetime2")]
public DateTime RegistrationDate { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
{
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
return userIdentity;
}
}
客户端.cs
public class Client : ApplicationUser
{
}
驱动程序.cs
public class Driver: ApplicationUser
{
private ICollection<Country> countriesOfOperation;
public Driver()
{
this.countriesOfOperation = new HashSet<Country>();
}
[Column(TypeName = "datetime2")]
public DateTime DateOfBirth { get; set; }
[MaxLength(250)]
public string AboutMe { get; set; }
public Genders Gender { get; set; }
public virtual ICollection<Country> CountriesOfOperation
{
get { return this.countriesOfOperation; }
set { this.countriesOfOperation = value; }
}
}
这意味着我必须像这样在 AccountController 中创建注册方法:
[AllowAnonymous]
[Route("Clients/register")]
public async Task<IHttpActionResult> RegisterClient(ClientRegisterBindingModel model)
{
var user = new Client()
{
UserName = model.Email,
Email = model.Email,
RegistrationDate = DateTime.Now
};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
驱动程序类也是如此。当然,继承重用了 UserName、Email、PasswordHash 等内容,但这也意味着我必须为我添加的每种类型的用户创建类似 register 的方法。这让帐户管理非常痛苦。
2) 通过使用引用 ApplicationUser 的字段将客户端和驱动程序保存在单独的表中
public class Client
{
public string FirstName { get; set; }
public ApplicationUser Account { get; set; }
}
这似乎好一点,但要访问客户端的用户名,我必须执行clientInstance.Account.UserName 之类的操作,这似乎仍然不够优雅。
我对这项技术还很陌生,而且我还没有探索过它的所有功能,所以我可能会遗漏一些相当明显的东西。提前致谢。
【问题讨论】:
-
将客户和司机保持在同一个表中,只是他们有不同的 accountId 可能有一个名为
Group的列并手动创建它们,将所有客户作为第 1 组,将所有司机作为第 2 组 -
@MethodMan,将它们放在同一个表中不会留下太多未使用的列吗?例如,驱动程序类有 3-4 个客户端没有的字段,这意味着对于客户端行,它们必须为 NULL。
-
很高兴看到您的数据库布局示例,您可以使用 2 个表并构造一个联接查询,我认为您正在使方法变得比它需要的更难。 . 有很多方法可以剥这只猫的皮
-
@arnaudoff 我认为更好的方法是通过分配适当的角色来区分两种类型的用户。
-
@AndriiTsok 所说的基于角色的身份验证是什么?
标签: c# asp.net asp.net-web-api