1

I am struggling to understand why my AsyncLocal isn't working as expected. Please see the bits of code below. The controller is decorated with my ApiExceptionFilterAttribute to be able to handle any exceptions thrown by methods. The filter is scoped and my AsyncLocal is initialized to "123" on start. The "DoWork" method sets the AsyncLocal to "666" and throws. I would expect that OnExceptionAsync sees "666" but in reality it's "123". Worst of all "DoWork" does not even see "123" but a null instead.

I was under the impression the controller method and the exception filter are both running in the same async flow. Either this is not true or I am missing something obvious. Any pointers are appreciated.

public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
{
    public static readonly AsyncLocal<string> AsyncLocal = new();

    public ApiExceptionFilterAttribute()
    {
        AsyncLocal.Value = "123";
    }

    public override async Task OnExceptionAsync(ExceptionContext context)
    {
        var value = AsyncLocal.Value;
        // "value" is "123" here
    }
}

services.AddScoped<ApiExceptionFilterAttribute>();


[ServiceFilter(typeof(ApiExceptionFilterAttribute))]
public class MyController : Controller
{
    public async Task<IActionResult> DoWork(CancellationToken cancellationToken)
    {
        ApiExceptionFilterAttribute.AsyncLocal.Value = "666";
        throw new Exception();
    }
}
wpfwannabe
  • 14,587
  • 16
  • 78
  • 129
  • See point #2 on this answer: https://stackoverflow.com/a/64816079/9604 I cant confirm this as I'm not an expert here, but I would assume throwing an Exception falls under "Until something happens that would require the context to change". Hopefully someone gives a real answer because I am wondering why also. – mxmissile Sep 21 '22 at 17:59
  • See https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#avoid-setting-asynclocalt-values-outside-of-async-methods – davidfowl Sep 22 '22 at 03:57
  • Hi @wpfwannabe, I think you can check this answer here: https://stackoverflow.com/a/69803325/11398810 – Rena Sep 22 '22 at 09:30
  • Thanks everyone! I do think that the comment of @davidfowl answers the question. Can you please phrase it as an answer too? – wpfwannabe Sep 26 '22 at 13:31

0 Answers0