Last post Jul 28, 2020 10:10 AM by YihuiSun
Jul 27, 2020 04:08 PM|pacojones|LINK
Hi all, I have a bunch of APIs and there are a few well known headers. Depending on the operation that is being called, required headers also change.
Apart from this, we use a classic n-tier architecture, so on a lower layer I need to make decisions based on some of those headers.
The simplest path I had to do this was reading all headers one by one on my controller declaring them [FromHeader] and so on, or create a class to represent all headers, read them per each operation then pass that parameter to every further internal call.
That seemed quite odd, so each method has to known the "headers" object.
So what I found out was why not create a middleware, read headers per request, save it on HttpContext then with DI get that object on demand?
public class HeadersMiddleware
private readonly RequestDelegate _next;
private readonly IHeadersReader _headersReader;
public HeadersMiddleware(RequestDelegate next, IHeadersReader headersReader)
_next = next;
_headersReader = headersReader;
public async Task Invoke(HttpContext context)
Then I have an accessor that I declare on my startup:
public class HeadersAccessor : IHeadersAccessor
private IHttpContextAccessor _httpContextAccessor;
public RequestContextAccessor(IHttpContextAccessor accessor)
this._httpContextAccessor = accessor;
public HeadersObject GetContext()
_httpContextAccessor.HttpContext.Items.TryGetValue("MyHeadersObj", value: out object contextRequest);
if (contextRequest == null)
return new HeadersObject ();
return contextRequest as HeadersObject ;
So when I need to read one or more headers this is just a dependency that is resolver at the upper layer.
I've noticed that this has a few consequences, specially the dependencies where this is needed, I ended up changing them from Singleton to Scoped.
My question is if there is some sort of disadvantage on doing this or some sort of performance problems by doing things like this, because it is tempting and generically solves my need.
Jul 28, 2020 10:10 AM|YihuiSun|LINK
As far as I know, using Scoped does not cause performance problems.When using Scoped, each client request (connection)
will create a scope lifetime service. Although this request will take a little time, it can be ignored.