在我的旧非OWIN API中,我使用MessageHanlder来记录所有HttpRequests和HttpResponses。这是MessageHandler:
public class MessageHandler : DelegatingHandler
{
private static readonly ILog RequestApiLogger = LogManager.GetLogger("RequestApiPacketLogger");
private static readonly ILog ResponseApiLogger = LogManager.GetLogger("ResponseApiPacketLogger");
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var correlationId = Guid.NewGuid();
RequestApiLogger.LogHttpRequest(request, correlationId);
return await base.SendAsync(request, cancellationToken).ContinueWith(
task =>
{
var response = task.Result;
response.Headers.Add("http-tracking-id", correlationId.ToString("D"));
ResponseApiLogger.LogHttpResponse(response, correlationId);
return response;
}, cancellationToken);
}
}
但是,在我的新项目中,我可以编写自定义OWIN中间件,使用类似这样的OwinContext做类似的事情:
//use an alias for the OWIN AppFunc
using AppFunc = Func<IDictionary<string, object>, Task>;
public class LoggingMiddleware
{
private readonly AppFunc _next;
public LoggingMiddleware(AppFunc next)
{
_next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
IOwinContext context = new OwinContext(environment);
// Get the identity
var identity = (context.Request.User != null && context.Request.User.Identity.IsAuthenticated)
? context.Request.User.Identity.Name
: "(anonymous)";
// Buffer the request (body is a string, we can use this to log the request later
var requestBody = new StreamReader(context.Request.Body).ReadToEnd();
var requestData = Encoding.UTF8.GetBytes(requestBody);
context.Request.Body = new MemoryStream(requestData);
var apiPacket = new ApiPacket
{
CallerIdentity = identity,
Request = requestBody,
RequestLength = context.Request.Body.Length
};
// Buffer the response
var responseBuffer = new MemoryStream();
var responseStream = context.Response.Body;
context.Response.Body = responseBuffer;
// add the "http-tracking-id" response header so the user can correlate back to this entry
var responseHeaders = (IDictionary<string, string[]>)environment["owin.ResponseHeaders"];
responseHeaders["http-tracking-id"] = new[] { apiPacket.TrackingId.ToString("d") };
await _next.Invoke(environment);
responseBuffer.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(responseBuffer);
apiPacket.Response = await reader.ReadToEndAsync();
apiPacket.ResponseLength = context.Response.ContentLength ?? 0;
WriteRequestHeaders(context.Request, apiPacket);
WriteResponseHeaders(context.Response, apiPacket);
// You need to do this so that the response we buffered is flushed out to the client application.
responseBuffer.Seek(0, SeekOrigin.Begin);
await responseBuffer.CopyToAsync(responseStream);
//TODO: persist the ApiPacket in the database
}
private static void WriteRequestHeaders(IOwinRequest request, ApiPacket packet)
{
packet.Verb = request.Method;
packet.RequestUri = request.Uri;
packet.RequestHeaders = "{\r\n" + string.Join(Environment.NewLine, request.Headers.Select(kv => "\t" + kv.Key + "=" + string.Join(",", kv.Value))) + "\r\n}";
}
private static void WriteResponseHeaders(IOwinResponse response, ApiPacket packet)
{
packet.StatusCode = response.StatusCode;
packet.ReasonPhrase = response.ReasonPhrase;
packet.ResponseHeaders = "{\r\n" + string.Join(Environment.NewLine, response.Headers.Select(kv => "\t" + kv.Key + "=" + string.Join(",", kv.Value))) + "\r\n}";
}
}
我正在使用log4net将信息写入SQL2012数据库。两种方式都实现了我的目标但是,我正在寻找使用一种方法而不是另一种方法的理由。我应该使用自定义OWIN中间件还是MessageHandler,为什么?提前谢谢。
答案 0 :(得分:0)
由于您已经有MessageHandler
个实现,我建议您使用它,除非您有其他原因。
但是,如果您有其他OwinMiddleware
组件需要(或将从中受益)日志记录功能,那么将我的日志迁移到OwinMiddleware
的一个正当理由是假的,您正在使用WebApi
,MessageHandlers
将在请求管道中的所有OwinMiddleware
之后运行。
答案 1 :(得分:0)
看起来我将使用OWIN中间件。我发现在MessageHandler中,Principal.IIdentity尚未解决。例如,如果我在我的消息处理程序,API控制器的构造函数和API方法中放置断点,这就是我所看到的(按顺序)。
使用邮件处理程序
因此,我无法撤出并在MessageHandler中记录授权用户的id。
然而,当使用OWIN中间件时,Principal.IIdentity IS在那里解析,所以我可以在那时将userId写入我的日志表。这就是我决定使用中间件的原因。
也许某人可以提供一些关于IIDentity何时在API项目中设置的清晰度。