asp.net core - How to inject HttpHeader value in controller? -
i have web api developed using asp.net core api. every incoming request has custom header value inserted. eg x-correlationid
. controller use value logging , tracing request. i'm reading value in each controller below
[route("api/[controller]")] public class documentcontroller : controller { private ilogger<transformcontroller> _logger; private string _correlationid = null; public documentcontroller(ilogger<documentcontroller > logger) { _logger = logger; _correlationid = httpcontext.request.headers["x-correlationid"]; } [httppost] public async task<inttransform([frombody]requestwrapper request) { _logger.loginformation("start task. correlationid:{0}", _correlationid); // here _logger.loginformation("end task. correlationid:{0}", _correlationid); return result; } }
i think against di rules.
instead of reading value inside controller's constructor, want inject value in controller's constructor.
or
can middleware read x-correlationid
, *somehow*
make available controllers don't have inject in controller?
what better option here?
instead of reading value inside controller's constructor, want inject value in controller's constructor.
you can't inject value constructor of api controller, because @ time of construction httpcontext
going null
.
one "injection-style" option use fromheaderattribute
in actions:
[httppost] public async task<int> transform( [frombody]requestwrapper request, [fromheader(name="x-correlationid")] string correlationid) { return result; }
can middleware read x-correlationid , somehow make available controllers don't have inject in controller?
i think middleware solution overkill need. instead, can create custom base class derives controller
, have api controllers derive that.
public class mycontrollerbase : controller { protected string correlationid => httpcontext?.request.headers["x-correlationid"] ?? string.empty; } [route("api/[controller]")] public class documentcontroller : mycontrollerbase { private ilogger<transformcontroller> _logger; public documentcontroller(ilogger<documentcontroller> logger) { _logger = logger; } [httppost] public async task<inttransform([frombody]requestwrapper request) { _logger.loginformation($"start task. correlationid:{correlationid}"); // here _logger.loginformation($"end task. correlationid:{correlationid}"); return result; } }
Comments
Post a Comment