我有几个ASP.Net MVC和WebAPI项目.其中大多数都是最新的(MVC 5/WebAPI 2).我一直在仔细检查我的安全假设,因为我正在实现一个全局过滤器(用于MVC)和一个委托处理程序(用于WebAPI)来统一整个系统的安全性.
在这种情况下,我遇到了一些文章和帖子(见下文),其中说你应该总是设置UseTaskFriendlySynchronizationContext
为true
(默认为false
).这对我来说似乎很奇怪,因为即使在VS2013中使用MVC 5和WebAPI 2新项目模板(以及ASP.Net WebForms模板)也根本不设置此应用程序设置.
关于此设置的MSDN文档几乎不存在,我发现的帖子确实说它是异步编程所必需的,似乎是在WebForms的上下文中.
所以这是我的问题:
以下是我见过的一些文章UseTaskFriendlySynchronizationContext
:
SynchronizationContext
由Marcus van Houdt 理解ASP.NET中的内容一些文章真正帮助我掌握了所有这些东西的作用,从未提及UseTaskFriendlySynchronizationContext
:
asp.net asp.net-mvc synchronizationcontext async-await asp.net-web-api
在使用ConfigureAwait(false)的引用库中使用Thread.CurrentPrincipal的声明会造成任何问题,或者ExecutionContext的逻辑调用上下文的流动会在那里照顾我吗?(到目前为止,我的阅读和测试表明它会).
示例WebAPI控制器操作:
[CustomAuthorizeThatSetsCurrentUsersClaimsToThreadCurrentContextAndHttpContextCurrentUser]
public async Task<Order> Get(int orderId)
{
return await _orderBusinessLogicLibrary.LoadAsync(orderId); // defaults to .ConfigureAwait(true)
}
Run Code Online (Sandbox Code Playgroud)
来自外部引用库的示例加载函数:
[ClaimsPrincipalPermission(
SecurityAction.Demand,
Operation="Read",
Resource="Orders")]
[ClaimsPrincipalPermission(
SecurityAction.Demand,
Operation="Read",
Resource="OrderItems")]
public async Task<Order> Load(int orderId)
{
var order = await _repository.LoadOrderAsync(orderId).ConfigureAwait(false);
// here's the key line.. assuming this lower-level function is also imposing
// security constraints in the same way this method does, would
// Thread.CurrentPrincipal still be correct inside the function below?
order.Items = await _repository.LoadOrderItemsAsync(orderId).ConfigureAwait(false);
return order;
}
Run Code Online (Sandbox Code Playgroud)
此外,答案不能是"那么不要使用ConfigureAwait(false)!".这可能会导致其他问题,例如死锁(请勿在异步代码上阻止).
claims-based-identity synchronizationcontext async-await current-principal executioncontext
好吧,所以我遇到了一个奇怪的小问题,坦白说我没有想法.我想把它扔出去看看我是否遗漏了一些我做错了,或者ConcurrentDictionary无法正常工作的东西.这是代码:
(Cache是一个包含静态ConcurrentDictionary键的类)
var tmp = Cache.Keys.GetOrAdd(type,
key =>
{
var keys = context.GetKeys(key);
if (keys.Count() == 1)
{
return new KeyInfo
{
Name = keys.First().Name,
Info = key.GetInfo(keys.First().Name)
};
}
return null;
});
if (tmp == null)
Cache.Keys.TryRemove(type, out tmp);
return tmp;
Run Code Online (Sandbox Code Playgroud)
问题是,偶尔tmp
会null
导致TryRemove
线路运行,但return null;
上面的线路永远不会被击中.由于这return null
是唯一将null
进入词典,它永远不会运行,怎么可能tmp
永远是null
?
包括Cache类(此代码不使用SetNames):
public class Cache
{
public static ConcurrentDictionary<Type, Info> Keys = new ConcurrentDictionary<Type, Info>();
public static ConcurrentDictionary<Type, string> SetNames …
Run Code Online (Sandbox Code Playgroud)