ASP.Net Web API 2 / .Net4.5.2を使用しています。
バックグラウンドワークアイテムをキューに入れるときに、呼び出し元のプリンシパルを保持しようとしています。そのために、私は次のことを試みています。
Thread.CurrentPrincipal = callingPrincipal;
しかし、そうすると、ObjectDisposedExceptionが発生します。
System.ObjectDisposedException:セーフハンドルが閉じられました
現在のプリンシパルをバックグラウンドワークアイテム内に保持するにはどうすればよいですか?
どういうわけか元本のコピーを作成できますか?
public void Run<T>(Action<T> action)
{
_logger.Debug("Queueing background work item");
var callingPrincipal = Thread.CurrentPrincipal;
HostingEnvironment.QueueBackgroundWorkItem(token =>
{
try
{
// UNCOMMENT - THROWS EXCEPTION
// Thread.CurrentPrincipal = callingPrincipal;
_logger.Debug("Executing queued background work item");
using (var scope = DependencyResolver.BeginLifetimeScope())
{
var service = scope.Resolve<T>();
action(service);
}
}
catch (Exception ex)
{
_logger.Fatal(ex);
}
finally
{
_logger.Debug("Completed queued background work item");
}
});
}
結局のところClaimsPrincipal
、今コピーコンストラクタを持っています。
var principal = new ClaimsPrincipal(Thread.CurrentPrincipal);
これにより、すべてのID情報とクレーム情報を保持しながら、問題が解決したようです。完全な機能は次のとおりです。
public void Run<T>(Action<T> action)
{
_logger.Debug("Queueing background work item");
var principal = new ClaimsPrincipal(Thread.CurrentPrincipal);
HostingEnvironment.QueueBackgroundWorkItem(token =>
{
try
{
Thread.CurrentPrincipal = principal;
_logger.Debug("Executing queued background work item");
using (var scope = DependencyResolver.BeginLifetimeScope())
{
var service = scope.Resolve<T>();
action(service);
}
}
catch (Exception ex)
{
_logger.Fatal(ex);
}
finally
{
_logger.Debug("Completed queued background work item");
}
});
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加