├── .gitignore
├── LICENSE
├── README.md
└── src
├── .gitignore
├── HttpTrackingMiddleware.sln
├── SpringComp.Interop
├── HttpEntry.cs
├── IHttpTrackingStore.cs
└── SpringComp.Interop.csproj
├── SpringComp.Owin
├── ContentStream.cs
├── HttpTrackingBuilderExtensions.cs
├── HttpTrackingMiddleware.cs
├── HttpTrackingOptions.cs
├── HttpTrackingServiceCollectionExtensions.cs
└── SpringComp.Owin.csproj
└── WebApi
├── Controllers
└── WeatherForecastController.cs
├── HttpTrackingConsoleStore.cs
├── Program.cs
├── Properties
└── launchSettings.json
├── Startup.cs
├── WeatherForecast.cs
├── WebApi.csproj
├── appsettings.Development.json
└── appsettings.json
/.gitignore:
--------------------------------------------------------------------------------
1 | bin/
2 | obj/
3 | packages/
4 |
5 | # Ignore files built by Visual Studio
6 |
7 | *.suo
8 | *.user
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | HttpTrackingMiddleware
2 | ======================
3 |
4 | A custom [Owin](http://owin.org/) Middleware to track details of an HTTP request and response.
5 |
6 | This is a sample of a custom Owin Middleware, designed to track details and HTTP request and response.
7 | It allows you to record extensive details about an HTTP request to a durable store and return the response
8 | to the caller with a *Tracking Identifier*.
9 |
10 | 
11 |
12 | That way, in case of an error, the caller can call your customer support staff to troubleshoot the real cause
13 | of an error.
14 |
15 | ## Rationale and Explanations
16 |
17 | You can find a detailed walkthrough about designing this Middleware in the following post from my Blog:
18 |
19 | [http://maximelabelle.wordpress.com/2014/10/08/capturing-rest-api-calls-with-an-owin-middleware/](http://maximelabelle.wordpress.com/2014/10/08/capturing-rest-api-calls-with-an-owin-middleware/)
20 |
--------------------------------------------------------------------------------
/src/.gitignore:
--------------------------------------------------------------------------------
1 | \.vs/
2 | [Bb]in/
3 | [Oo]bj/
4 |
--------------------------------------------------------------------------------
/src/HttpTrackingMiddleware.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26124.0
5 | MinimumVisualStudioVersion = 15.0.26124.0
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpringComp.Interop", "SpringComp.Interop\SpringComp.Interop.csproj", "{A40FBB76-FEEA-40D6-AB09-02343262CE84}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpringComp.Owin", "SpringComp.Owin\SpringComp.Owin.csproj", "{51680F00-C4AD-4F04-B953-2B3E278AD7E3}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi", "WebApi\WebApi.csproj", "{932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Debug|x64 = Debug|x64
16 | Debug|x86 = Debug|x86
17 | Release|Any CPU = Release|Any CPU
18 | Release|x64 = Release|x64
19 | Release|x86 = Release|x86
20 | EndGlobalSection
21 | GlobalSection(SolutionProperties) = preSolution
22 | HideSolutionNode = FALSE
23 | EndGlobalSection
24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
25 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Debug|Any CPU.Build.0 = Debug|Any CPU
27 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Debug|x64.ActiveCfg = Debug|Any CPU
28 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Debug|x64.Build.0 = Debug|Any CPU
29 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Debug|x86.ActiveCfg = Debug|Any CPU
30 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Debug|x86.Build.0 = Debug|Any CPU
31 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Release|Any CPU.ActiveCfg = Release|Any CPU
32 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Release|Any CPU.Build.0 = Release|Any CPU
33 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Release|x64.ActiveCfg = Release|Any CPU
34 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Release|x64.Build.0 = Release|Any CPU
35 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Release|x86.ActiveCfg = Release|Any CPU
36 | {A40FBB76-FEEA-40D6-AB09-02343262CE84}.Release|x86.Build.0 = Release|Any CPU
37 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
38 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
39 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Debug|x64.ActiveCfg = Debug|Any CPU
40 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Debug|x64.Build.0 = Debug|Any CPU
41 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Debug|x86.ActiveCfg = Debug|Any CPU
42 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Debug|x86.Build.0 = Debug|Any CPU
43 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
44 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Release|Any CPU.Build.0 = Release|Any CPU
45 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Release|x64.ActiveCfg = Release|Any CPU
46 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Release|x64.Build.0 = Release|Any CPU
47 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Release|x86.ActiveCfg = Release|Any CPU
48 | {51680F00-C4AD-4F04-B953-2B3E278AD7E3}.Release|x86.Build.0 = Release|Any CPU
49 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
50 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Debug|Any CPU.Build.0 = Debug|Any CPU
51 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Debug|x64.ActiveCfg = Debug|Any CPU
52 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Debug|x64.Build.0 = Debug|Any CPU
53 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Debug|x86.ActiveCfg = Debug|Any CPU
54 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Debug|x86.Build.0 = Debug|Any CPU
55 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Release|Any CPU.ActiveCfg = Release|Any CPU
56 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Release|Any CPU.Build.0 = Release|Any CPU
57 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Release|x64.ActiveCfg = Release|Any CPU
58 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Release|x64.Build.0 = Release|Any CPU
59 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Release|x86.ActiveCfg = Release|Any CPU
60 | {932C39A7-EBC4-43D7-A1EF-39DE6A20AF38}.Release|x86.Build.0 = Release|Any CPU
61 | EndGlobalSection
62 | EndGlobal
63 |
--------------------------------------------------------------------------------
/src/SpringComp.Interop/HttpEntry.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace SpringComp.Interop
5 | {
6 | ///
7 | /// A simple class to hold details of an HTTP call.
8 | ///
9 | public sealed class HttpEntry
10 | {
11 | ///
12 | /// Initialize a new instance of the class.
13 | ///
14 | public HttpEntry()
15 | {
16 | TrackingId = Guid.NewGuid();
17 | CallDateTime = DateTime.UtcNow;
18 | }
19 |
20 | ///
21 | /// An unique identifier for the HTTP call.
22 | ///
23 | public Guid TrackingId { get; private set; }
24 |
25 | ///
26 | /// Identity of the caller.
27 | ///
28 | public string CallerIdentity { get; set; }
29 |
30 | ///
31 | /// Timestamp at which the HTTP call took place.
32 | ///
33 | public DateTime CallDateTime { get; set; }
34 |
35 | ///
36 | /// Verb associated with the HTTP call.
37 | ///
38 | public string Verb { get; set; }
39 |
40 | ///
41 | /// Http request URI.
42 | ///
43 | public string RequestUri { get; set; }
44 |
45 | ///
46 | /// Http request headers.
47 | ///
48 | public IDictionary RequestHeaders { get; set; }
49 |
50 | ///
51 | /// Http request content-length
52 | /// In the case of chunked transfer encoding,
53 | /// the request headers do not mention the content length.
54 | ///
55 | public long RequestLength { get; set; }
56 |
57 | ///
58 | /// Http request body, if any.
59 | ///
60 | public string Request { get; set; }
61 |
62 | ///
63 | /// Http response status code.
64 | ///
65 | public int StatusCode { get; set; }
66 |
67 | ///
68 | /// Http response headers.
69 | ///
70 | public IDictionary ResponseHeaders { get; set; }
71 |
72 | ///
73 | /// Http response content-length
74 | /// In the case of chunked transfer encoding,
75 | /// the response headers do not mention the content length.
76 | ///
77 | public long ResponseLength { get; set; }
78 |
79 | ///
80 | /// Http response body.
81 | ///
82 | public string Response { get; set; }
83 |
84 |
85 | ///
86 | /// Timestamp representing the duration of the HTTP call.
87 | ///
88 | public TimeSpan CallDuration { get; set; }
89 | }
90 | }
--------------------------------------------------------------------------------
/src/SpringComp.Interop/IHttpTrackingStore.cs:
--------------------------------------------------------------------------------
1 | using System.Threading.Tasks;
2 |
3 | namespace SpringComp.Interop
4 | {
5 | ///
6 | /// Interface for tracking details about HTTP calls.
7 | ///
8 | public interface IHttpTrackingStore
9 | {
10 | ///
11 | /// Persist details of an HTTP call into durable storage.
12 | ///
13 | ///
14 | ///
15 | Task InsertRecordAsync(HttpEntry record);
16 | }
17 | }
--------------------------------------------------------------------------------
/src/SpringComp.Interop/SpringComp.Interop.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/src/SpringComp.Owin/ContentStream.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Text;
4 | using System.Text.RegularExpressions;
5 | using System.Threading;
6 | using System.Threading.Tasks;
7 |
8 | namespace SpringComp.Owin
9 | {
10 | ///
11 | /// A class to wrap a stream for interception purposes
12 | /// and recording the number of bytes written to or read from
13 | /// the wrapped stream.
14 | ///
15 | public class ContentStream : Stream
16 | {
17 | protected readonly Stream buffer_;
18 | protected readonly Stream stream_;
19 |
20 | private long contentLength_ = 0L;
21 |
22 | ///
23 | /// Initialize a new instance of the class.
24 | ///
25 | /// To hold tracked data.
26 | /// The HTTP stream.
27 | public ContentStream(Stream buffer, Stream stream)
28 | {
29 | buffer_ = buffer;
30 | stream_ = stream;
31 | }
32 |
33 | ///
34 | /// Gets or sets the maximum recorded length.
35 | /// Once the number of bytes read or written
36 | /// is reach, the buffer no longer receives data.
37 | ///
38 | public long MaxRecordedLength { get; set; }
39 |
40 | ///
41 | /// Returns the recorded length of the underlying stream.
42 | ///
43 | public virtual long ContentLength => contentLength_;
44 |
45 | ///
46 | /// Reads the content of the stream as a string.
47 | ///
48 | /// If the contentType is not specified (null) or does not
49 | /// refer to a string, this function returns the content type
50 | /// followed by the number of bytes in the response.
51 | ///
52 | /// If the contentType is one of the following values, the
53 | /// resulting content is decoded as a string and truncated to
54 | /// the maximum count specified.
55 | ///
56 | /// HTTP header content type.
57 | /// Max number of bytes returned from the stream.
58 | ///
59 | public async Task ReadContentAsync(string contentType, long maxCount)
60 | {
61 | if (!IsTextContentType(contentType))
62 | {
63 | contentType = String.IsNullOrEmpty(contentType) ? "N/A" : contentType;
64 | return $"{contentType} [{ContentLength} bytes]";
65 | }
66 |
67 | buffer_.Seek(0, SeekOrigin.Begin);
68 |
69 | var length = Math.Min(ContentLength, maxCount);
70 |
71 | var buffer = new byte[length];
72 | var count = await buffer_.ReadAsync(buffer, 0, buffer.Length);
73 |
74 | return
75 | GetEncoding(contentType)
76 | .GetString(buffer, 0, count)
77 | ;
78 | }
79 |
80 | protected Task WriteContentAsync(byte[] buffer, int offset, int count)
81 | {
82 | return buffer_.WriteAsync(buffer, offset, count);
83 | }
84 |
85 | #region Implementation
86 |
87 | private static bool IsTextContentType(string contentType)
88 | {
89 | if (contentType == null)
90 | return false;
91 |
92 | var isTextContentType =
93 | contentType.StartsWith("application/json") ||
94 | contentType.StartsWith("application/xml") ||
95 | contentType.StartsWith("text/")
96 | ;
97 | return isTextContentType;
98 | }
99 |
100 | private static Encoding GetEncoding(string contentType)
101 | {
102 | var charset = "utf-8";
103 | var regex = new Regex(@";\s*charset=(?[^\s;]+)");
104 | var match = regex.Match(contentType);
105 | if (match.Success)
106 | charset = match.Groups["charset"].Value;
107 |
108 | try
109 | {
110 | return Encoding.GetEncoding(charset);
111 | }
112 | catch
113 | {
114 | return Encoding.UTF8;
115 | }
116 | }
117 |
118 | #endregion
119 |
120 | #region System.IO.Stream Overrides
121 |
122 | public override bool CanRead => stream_.CanRead;
123 | public override bool CanSeek => stream_.CanSeek;
124 | public override bool CanWrite => stream_.CanWrite;
125 |
126 | public override Task FlushAsync(CancellationToken cancellationToken)
127 | {
128 | return stream_.FlushAsync(cancellationToken);
129 | }
130 |
131 | public override void Flush()
132 | {
133 | throw new NotSupportedException();
134 | }
135 |
136 | public override long Length => stream_.Length;
137 |
138 | public override long Position
139 | {
140 | get => stream_.Position;
141 | set => stream_.Position = value;
142 | }
143 |
144 | public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
145 | {
146 | // read content from the request stream
147 |
148 | count = await stream_.ReadAsync(buffer, offset, count, cancellationToken);
149 | contentLength_ += count;
150 |
151 | // record the read content into our temporary buffer
152 |
153 | if (count != 0 && contentLength_ < MaxRecordedLength)
154 | await WriteContentAsync(buffer, offset, count);
155 |
156 | return count;
157 | }
158 |
159 | public override int Read(byte[] buffer, int offset, int count)
160 | {
161 | throw new NotSupportedException();
162 | }
163 |
164 | public override long Seek(long offset, SeekOrigin origin)
165 | {
166 | return stream_.Seek(offset, origin);
167 | }
168 |
169 | public override void SetLength(long value)
170 | {
171 | stream_.SetLength(value);
172 | }
173 |
174 | public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
175 | {
176 | // store the bytes into our local stream
177 |
178 | await WriteContentAsync(buffer, 0, count);
179 |
180 | // write the bytes to the response stream
181 | // and record the actual number of bytes written
182 |
183 | await stream_.WriteAsync(buffer, offset, count, cancellationToken);
184 | contentLength_ += count;
185 | }
186 |
187 | public override void Write(byte[] buffer, int offset, int count)
188 | {
189 | throw new NotSupportedException();
190 | }
191 |
192 | #endregion
193 |
194 | #region IDisposable Implementation
195 |
196 | protected override void Dispose(bool disposing)
197 | {
198 | buffer_.Dispose();
199 | }
200 |
201 | #endregion
202 | }
203 | }
--------------------------------------------------------------------------------
/src/SpringComp.Owin/HttpTrackingBuilderExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.AspNetCore.Builder;
3 | using Microsoft.Extensions.DependencyInjection;
4 | using Microsoft.Extensions.Options;
5 |
6 | namespace SpringComp.Owin
7 | {
8 | public static class HttpTrackingAppBuilderExtensions
9 | {
10 | public static IApplicationBuilder UseHttpTracking(this IApplicationBuilder app)
11 | {
12 | if (app == null)
13 | {
14 | throw new ArgumentNullException(nameof(app));
15 | }
16 |
17 | var options = app.ApplicationServices.GetRequiredService>();
18 |
19 | return app.UseMiddleware(options.Value);
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/src/SpringComp.Owin/HttpTrackingMiddleware.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Threading.Tasks;
6 | using Microsoft.AspNetCore.Http;
7 | using Microsoft.AspNetCore.Http.Features;
8 | using SpringComp.Interop;
9 |
10 | namespace SpringComp.Owin
11 | {
12 | ///
13 | /// A simple Owin Middleware to capture HTTP requests and responses
14 | /// and store details of the call into a durable store.
15 | ///
16 | public sealed class HttpTrackingMiddleware
17 | {
18 | private readonly RequestDelegate next_;
19 |
20 | ///
21 | /// Default value for the TrackingId response header.
22 | /// This value can be changed by specifying the TrackingIdPropertyName
23 | /// in the class passed to the ctor.
24 | ///
25 | private readonly string trackingIdPropertyName_ = "http-tracking-id";
26 |
27 | private readonly IHttpTrackingStore storage_;
28 | private readonly long maxRequestLength_ = Int64.MaxValue;
29 | private readonly long maxResponseLength_ = Int64.MaxValue;
30 |
31 | ///
32 | /// Initialize a new instance of the class.
33 | ///
34 | /// A reference to the next OwinMiddleware object in the chain.
35 | /// A reference to an class.
36 | public HttpTrackingMiddleware(RequestDelegate next, HttpTrackingOptions options)
37 | {
38 | next_ = next;
39 | storage_ = options.TrackingStore;
40 |
41 | if (!string.IsNullOrEmpty(options.TrackingIdPropertyName))
42 | trackingIdPropertyName_ = options.TrackingIdPropertyName;
43 |
44 | maxRequestLength_ = options.MaximumRecordedRequestLength ?? maxRequestLength_;
45 | maxResponseLength_ = options.MaximumRecordedResponseLength ?? maxResponseLength_;
46 | }
47 |
48 | ///
49 | /// Processes the incoming HTTP call and capture details about
50 | /// the request, the response, the identity of the caller and the
51 | /// call duration to persistent storage.
52 | ///
53 | /// A reference to the HTTP context.
54 | ///
55 | public async Task Invoke(HttpContext context)
56 | {
57 | var request = context.Request;
58 | var response = context.Response;
59 |
60 | // capture details about the caller identity
61 |
62 | var identity =
63 | context.User != null && context.User.Identity.IsAuthenticated ?
64 | context.User.Identity.Name :
65 | "(anonymous)"
66 | ;
67 |
68 | var record = new HttpEntry
69 | {
70 | CallerIdentity = identity,
71 | };
72 |
73 | // replace the request stream in order to intercept downstream reads
74 |
75 | var requestBuffer = new MemoryStream();
76 | var requestStream = new ContentStream(requestBuffer, request.Body)
77 | {
78 | MaxRecordedLength = maxRequestLength_,
79 | };
80 | request.Body = requestStream;
81 |
82 | // replace the response stream in order to intercept downstream writes
83 |
84 | var responseBuffer = new MemoryStream();
85 | var responseStream = new ContentStream(responseBuffer, response.Body)
86 | {
87 | MaxRecordedLength = maxResponseLength_,
88 | };
89 | response.Body = responseStream;
90 |
91 | // add the "Http-Tracking-Id" response header
92 |
93 | context.Response.OnStarting(OnSendingHeaders, (response, record));
94 |
95 | // invoke the next middleware in the pipeline
96 |
97 | await next_.Invoke(context);
98 |
99 | // rewind the request and response buffers
100 | // and record their content
101 |
102 | WriteRequestHeaders(context, record);
103 | record.RequestLength = requestStream.ContentLength;
104 | record.Request = await WriteContentAsync(requestStream, record.RequestHeaders, maxRequestLength_);
105 |
106 | WriteResponseHeaders(response, record);
107 | record.ResponseLength = responseStream.ContentLength;
108 | record.Response = await WriteContentAsync(responseStream, record.ResponseHeaders, maxResponseLength_);
109 |
110 | // persist details of the call to durable storage
111 |
112 | await storage_.InsertRecordAsync(record);
113 | }
114 |
115 | private Task OnSendingHeaders(object state)
116 | {
117 | if (state is ValueTuple tuple)
118 | {
119 | var (response, record) = tuple;
120 | return OnSendingHeaders(response, record);
121 | }
122 |
123 | return Task.CompletedTask;
124 | }
125 | private async Task OnSendingHeaders(HttpResponse response, HttpEntry record)
126 | {
127 | // adding the tracking id response header so that the user
128 | // of the API can correlate the call back to this entry
129 |
130 | response.Headers.Add(trackingIdPropertyName_, new[] { record.TrackingId.ToString("d"), });
131 |
132 | await Task.CompletedTask;
133 | }
134 |
135 | private static void WriteRequestHeaders(HttpContext context, HttpEntry record)
136 | {
137 | var request = context.Request;
138 |
139 | record.Verb = request.Method;
140 | record.RequestUri = GetPath(context);
141 | record.RequestHeaders = request.Headers.ToDictionary(
142 | kvp => kvp.Key,
143 | kvp => kvp.Value.ToArray()
144 | );
145 | }
146 |
147 | private static void WriteResponseHeaders(HttpResponse response, HttpEntry record)
148 | {
149 | record.StatusCode = response.StatusCode;
150 | record.ResponseHeaders = response.Headers.ToDictionary(
151 | kvp => kvp.Key,
152 | kvp => kvp.Value.ToArray()
153 | );
154 | }
155 |
156 | private static async Task WriteContentAsync(ContentStream stream, IDictionary headers, long maxLength)
157 | {
158 | const string ContentTypeHeaderName = "Content-Type";
159 |
160 | var contentType =
161 | headers.ContainsKey(ContentTypeHeaderName) ?
162 | headers[ContentTypeHeaderName][0] :
163 | null
164 | ;
165 |
166 | return await stream.ReadContentAsync(contentType, maxLength);
167 | }
168 |
169 | private static string GetPath(HttpContext httpContext)
170 | {
171 | return httpContext.Features.Get()?.RawTarget ?? httpContext.Request.Path.ToString();
172 | }
173 | }
174 | }
--------------------------------------------------------------------------------
/src/SpringComp.Owin/HttpTrackingOptions.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using SpringComp.Interop;
3 |
4 | namespace SpringComp.Owin
5 | {
6 | ///
7 | /// Options for configuring the class.
8 | ///
9 | public sealed class HttpTrackingOptions
10 | {
11 | ///
12 | /// Interface to an implementation of a durable store for tracking calls.
13 | ///
14 | public IHttpTrackingStore TrackingStore { get; set; }
15 |
16 | ///
17 | /// Name of the HTTP response header property holding the tracking identifier.
18 | /// By default, the name of this property is "http-tracking-id"
19 | ///
20 | public string TrackingIdPropertyName { get; set; }
21 |
22 | ///
23 | /// The maximum number of bytes from the request to persist to durable storage.
24 | ///
25 | public long? MaximumRecordedRequestLength { get; set; }
26 |
27 | ///
28 | /// The maximum number of bytes from the response to persist to durable storage.
29 | ///
30 | public long? MaximumRecordedResponseLength { get; set; }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/SpringComp.Owin/HttpTrackingServiceCollectionExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.Extensions.DependencyInjection;
3 |
4 | namespace SpringComp.Owin
5 | {
6 | public static class HttpTrackingServiceCollectionExtensions
7 | {
8 | public static void AddHttpTracking(this IServiceCollection services, Action setupAction)
9 | {
10 | if (services == null)
11 | {
12 | throw new ArgumentNullException(nameof(services));
13 | }
14 |
15 | if (setupAction == null)
16 | {
17 | throw new ArgumentNullException(nameof(setupAction));
18 | }
19 |
20 | services.Configure(setupAction);
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/SpringComp.Owin/SpringComp.Owin.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/src/WebApi/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Mvc;
6 | using Microsoft.Extensions.Logging;
7 |
8 | namespace HttpTracking.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get()
28 | {
29 | var rng = new Random();
30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast
31 | {
32 | Date = DateTime.Now.AddDays(index),
33 | TemperatureC = rng.Next(-20, 55),
34 | Summary = Summaries[rng.Next(Summaries.Length)]
35 | })
36 | .ToArray();
37 | }
38 |
39 | [HttpPost]
40 | public async Task Post()
41 | {
42 | var buffer = new byte[1024];
43 | var count = 0;
44 |
45 | while ((count = await Request.Body.ReadAsync(buffer, 0, buffer.Length)) != 0)
46 | ;
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/WebApi/HttpTrackingConsoleStore.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text.Json;
5 | using SpringComp.Interop;
6 |
7 | namespace App
8 | {
9 | ///
10 | /// Dummy implementation of the interface to file, for illustration purposes.
11 | ///
12 | public sealed class HttpTrackingConsoleStore : IHttpTrackingStore
13 | {
14 | private readonly string path_ = Path.GetTempPath();
15 |
16 | public async System.Threading.Tasks.Task InsertRecordAsync(HttpEntry record)
17 | {
18 | var path = Path.Combine(path_, record.TrackingId.ToString("d"));
19 |
20 | await using (var stream = File.OpenWrite(path))
21 | await using (var writer = new StreamWriter(stream))
22 | await writer.WriteAsync(JsonSerializer.Serialize(record));
23 |
24 | Console.WriteLine("Verb: {0}", record.Verb);
25 | Console.WriteLine("RequestUri: {0}", record.RequestUri);
26 | WriteHeaders(record.RequestHeaders);
27 | Console.WriteLine("Request: {0}", record.Request);
28 | Console.WriteLine("RequestLength: {0}", record.RequestLength);
29 | Console.WriteLine();
30 |
31 | Console.WriteLine("StatusCode: {0}", record.StatusCode);
32 | WriteHeaders(record.ResponseHeaders);
33 | Console.WriteLine("Response: {0}", record.Response);
34 | Console.WriteLine("Content-Length: {0}", record.ResponseLength);
35 | Console.WriteLine();
36 |
37 | Console.WriteLine("FILE {0} saved.", path);
38 | }
39 |
40 | private static void WriteHeaders(IDictionary headers)
41 | {
42 | foreach (var (key, value) in headers)
43 | Console.WriteLine($"{key}: {string.Join(", ", value)}");
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/src/WebApi/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Hosting;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.Hosting;
8 | using Microsoft.Extensions.Logging;
9 |
10 | namespace HttpTracking
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/WebApi/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:2683",
8 | "sslPort": 44330
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "weatherforecast",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "HttpTracking": {
21 | "commandName": "Project",
22 | "launchBrowser": true,
23 | "launchUrl": "weatherforecast",
24 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
25 | "environmentVariables": {
26 | "ASPNETCORE_ENVIRONMENT": "Development"
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/WebApi/Startup.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using App;
6 | using Microsoft.AspNetCore.Builder;
7 | using Microsoft.AspNetCore.Hosting;
8 | using Microsoft.AspNetCore.HttpsPolicy;
9 | using Microsoft.AspNetCore.Mvc;
10 | using Microsoft.Extensions.Configuration;
11 | using Microsoft.Extensions.DependencyInjection;
12 | using Microsoft.Extensions.Hosting;
13 | using Microsoft.Extensions.Logging;
14 | using SpringComp.Owin;
15 |
16 | namespace HttpTracking
17 | {
18 | public class Startup
19 | {
20 | public Startup(IConfiguration configuration)
21 | {
22 | Configuration = configuration;
23 | }
24 |
25 | public IConfiguration Configuration { get; }
26 |
27 | // This method gets called by the runtime. Use this method to add services to the container.
28 | public void ConfigureServices(IServiceCollection services)
29 | {
30 | services.AddControllers();
31 | services.AddHttpTracking(options => {
32 | options.TrackingStore = new HttpTrackingConsoleStore();
33 | options.TrackingIdPropertyName = "x-tracking-id";
34 | options.MaximumRecordedRequestLength = 64 * 1024;
35 | options.MaximumRecordedResponseLength = 64 * 1024;
36 | });
37 | }
38 |
39 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
40 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
41 | {
42 | if (env.IsDevelopment())
43 | {
44 | app.UseDeveloperExceptionPage();
45 | }
46 |
47 | app.UseHttpsRedirection();
48 |
49 | app.UseRouting();
50 |
51 | app.UseAuthorization();
52 |
53 | app.UseHttpTracking();
54 |
55 | app.UseEndpoints(endpoints =>
56 | {
57 | endpoints.MapControllers();
58 | });
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/WebApi/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace HttpTracking
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/WebApi/WebApi.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/src/WebApi/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Debug",
5 | "System": "Information",
6 | "Microsoft": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/WebApi/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------