wpfwannabe
wpfwannabe

Reputation: 14877

AsyncLocal with controller method and a scoped exception filter

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();
    }
}

Upvotes: 1

Views: 247

Answers (0)

Related Questions