I am writing a piece of custom OWIN middleware to log all HTTP requests and their responses. I would like to โmatchโ them with tracking. Here is the code:
public class PacketTrackingMiddleware { private readonly AppFunc _next; public PacketTrackingMiddleware(AppFunc next) { _next = next; } public async Task Invoke(IDictionary<string, object> environment) { IOwinContext context = new OwinContext(environment); var request = context.Request; var response = context.Response;
I am having trouble adding the http-tracking-id identifier to the response header (these lines are here).
context.Response.OnSendingHeaders(state => { var ctx = state as IOwinContext; if (ctx == null) return; var resp = ctx.Response; resp.Headers.Add("http-tracking-id", new[] { apiPacket.TrackingId.ToString("d") }); }, context);
When adding a header, I sometimes get this error:
HttpException was not handled by user code.
Additional information: the server cannot add the header after the HTTP headers have been sent.
Edit 1: I test this by simply running the api that opens chrome for my http: // localhost: 64051 / address. If I look through any actual API ( http: // localhost: 64051 / api / Accounts / 21067 ), I do not get this error. Should I somehow just send 404 back while browsing to the root of the site?
c # owin
BBauer42
source share