背景
我正在使用.Net Core API来驱动歌词应用程序。用户可以注册,提交艺术家和歌词,并在此过程中获得荣誉/ XP积分。基本上是社区驱动的歌词网站。
码
这是我的ArtistController类:
[Route("api/artists")]
public class ArtistsController : Controller
{
private readonly IPermissionsService _permissionsService;
private readonly IArtistsService _artistsService;
public ArtistsController(IArtistsService artistsService, IPermissionsService permissionsService)
{
_permissionsService = permissionsService ?? throw new ArgumentNullException(nameof(permissionsService));
_artistsService = artistsService ?? throw new ArgumentNullException(nameof(artistsService));
}
[HttpGet("{slug}")]
[HttpGet("{slug}/lyrics", Name = "GetArtist")]
public async Task<IActionResult> GetArtist(string slug)
{
if (!_artistsService.ArtistExists(slug)) return NotFound();
var permissions = await _permissionsService.GetPermissions(HttpContext);
var artist = _artistsService.GetArtistBySlug(slug, permissions.UserId, permissions.IsAdministrator);
if (artist == null) return NotFound();
return Ok(artist);
}
// other methods omitted
}
本着可测试性的精神,我创建了一个
IPermissionsService
,这样,当我对控制器进行单元测试时,我可以轻松做到这一点,而不必担心HttpContext
和User
。这是
PermissionsService
类的代码:public class PermissionsService : IPermissionsService
{
private string _userId;
private bool _isAdministrator;
private HttpContext _httpContext;
private readonly UserManager<BbUser> _userManager;
public PermissionsService(UserManager<BbUser> userManager)
{
_userManager = userManager;
}
public async Task<Permissions> GetPermissions(HttpContext httpContext)
{
_httpContext = httpContext;
PopulateUserIdAndIsAdminFlag();
var permissions = new Permissions
{
UserId = _userId,
IsAdministrator = _isAdministrator
};
return await Task.Run(() => permissions);
}
private async void PopulateUserIdAndIsAdminFlag()
{
if (!IsAuthenticated()) return;
var username = _httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _userManager.FindByNameAsync(username);
var roles = await _userManager.GetRolesAsync(user);
_userId = user.Id;
_isAdministrator = roles.Contains("Admin");
}
private bool IsAuthenticated()
{
return _httpContext.User.Identity.IsAuthenticated;
}
}
问题
当我运行API并尝试调用该端点时。我收到以下错误:
在先前的操作完成之前,第二操作在此上下文上开始。不保证任何实例成员都是线程安全的。
消息很清楚,但是我不确定如何克服此错误。在将逻辑移到
PermissionsService
之前,我没有收到错误,并且一切正常! 最佳答案
从事async
工作的方法应返回Task
而不是void
,除非它们是事件处理程序。这将允许等待结果Task
。由于未等待PopulateUserIdAndIsAdminFlag
,因此您正在线程之间同时调用同一DbContext
实例。如果您遵循调用堆栈:
代码输入GetPermissions
您开始在PopulateUserIdAndIsAdminFlag
中工作,但不要等待它完成
代码立即从GetPermissions
返回(PopulateUserIdAndIsAdminFlag
中的代码仍在执行)
代码继续并在_artistsService
上调用方法
这可能导致多个线程同时调用DbContext,从而导致您的异常。
修改代码,以便等待PopulateUserIdAndIsAdminFlag
的结果。
更改您的代码以等待PopulateUserIdAndIsAdminFlag
方法,使其返回类型Task
等待PopulateUserIdAndIsAdminFlag
的结果
在Task
的末尾不再需要将结果包装在GetPermissions
中
我还建议重命名并添加后缀Async
,因为对于返回类型Task
的方法,这被认为是正确的命名约定。这将导致名为GetPermissionsAsync
和PopulateUserIdAndIsAdminFlagAsync
的方法
更改的代码:
public async Task<Permissions> GetPermissions(HttpContext httpContext)
{
_httpContext = httpContext;
// await result
await PopulateUserIdAndIsAdminFlag();
var permissions = new Permissions
{
UserId = _userId,
IsAdministrator = _isAdministrator
};
// wrapping the result in Task is no longer necessary
return permissions;
}
// change void to Task
private async Task PopulateUserIdAndIsAdminFlag()
{
if (!IsAuthenticated()) return;
var username = _httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _userManager.FindByNameAsync(username);
var roles = await _userManager.GetRolesAsync(user);
_userId = user.Id;
_isAdministrator = roles.Contains("Admin");
}