Search code examples
c#asp.net-corehttpcontext

Passing HttpContext to HttpResponse.OnStarting


Project that I'm working on contains middleware that uses OnStarting method and it passes HttpContext as a second argument like this:

context.Response.OnStarting(async state =>
{
    var context = (HttpContext)state;
    await SetSafeStatusCode(context);
}, context);
await _next(context);

I've seen examples that used this method without passing context like this:

context.Response.OnStarting(async () =>
{
    await SetSafeStatusCode(context);
});
await _next(context);

I didn't notice any difference while testing second option. Is there any reason for passing the same context that calls this method as a second argument?


Solution

  • The first method allows for the (possibly future) possibility that state and context are indeed different things. Maybe in certain current cases they ARE different things.

    It also allows for easier unit testing because the test can directly call OnStarting, without having to construct a complete HttpContext.