AsyncLocal für die Kontextfreigabe

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: AsyncLocal für die Kontextfreigabe

by Guest » 11 Jan 2025, 08:03

Ich habe eine .NET-Standardbibliothek, die von einer .NET v4.7.2-Anwendung genutzt wird. Ich habe eine benutzerdefinierte Middleware in der Anwendung, die den OWIN-Kontext extrahiert und ihn auf eine AsyncLocal-Variable setzt. Ist es möglich, über die Bibliothek auf diesen Kontext zuzugreifen?
BEARBEITEN: Die .NET-Standardbibliothek verfügt über die Logik für die Hangfire-Dashboard-Autorisierung (wie unten gezeigt). Ich benötige den OWIN-Kontext in der Methode Authorize().
HINWEIS: Da die Bibliothek auf .NET Standard abzielt, kann ich sie nicht verwenden new OwinContext(dashboardContextcontext.GetOwinEnvironment()) im Authorize. Da es außerdem keine direkte Möglichkeit gibt, HttpContext in .NET Standard abzurufen, habe ich versucht, es von Hangfire.AspNetCore abzurufen und Owin Context von dort zu extrahieren. Dies ist jedoch höchstwahrscheinlich ein Fehler, weil die Anwendung auf das .NET Framework abzielt. Versuchen Sie daher diese komplizierte Art, den Kontext zu teilen.

Code: Select all

public class OwinContextMiddleware
{
private readonly Func _next;

public OwinContextMiddleware(Func next)
{
_next = next;
}

public async Task Invoke(IDictionary environment)
{
// Capture the OWINContext
var owinContext = new OwinContext(environment);

// Store the OWINContext in AsyncLocal or HttpContext.Items
AsyncLocalStorage.Set(owinContext);

await _next(environment);
}
}

public static class AsyncLocalStorage
{
private static readonly AsyncLocal _current = new AsyncLocal();

public static void Set(IOwinContext context)
{
_current.Value = context;
}

public static IOwinContext Get()
{
return _current.Value;
}
}
Beim Start der .NET Framework-Anwendung habe ich Folgendes:

Code: Select all

app.Use(typeof(OwinContextMiddleware));
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[] {
new DashboardAuthorization()
//code
}
});
Die .NET-Standardbibliothek verfügt über die Hangfire-Autorisierungslogik:

Code: Select all

public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
private readonly BasicAuthAuthorizationFilterOptions _options;

public BasicAuthAuthorizationFilter(BasicAuthAuthorizationFilterOptions options)
{
_options = options;
}

public bool Authorize(DashboardContext context)
{
//This is where I need to access the OWIN Context
}
}

Top