我正在研究ASP.NET Web Api項目並使其接受URL中的版本信息。Web Api - 外部控制器的請求參數
例如:
- API/V1/myController的
- API/V2/myController的
現在我想獲得請求的版本V1,V2自定義內LayoutRenderer爲Nlog
。通常我會像下面的例子那樣做。
[LayoutRenderer("Version")]
public class VersionLayoutRenderer : LayoutRenderer
{
protected override void Append(System.Text.StringBuilder builder, NLog.LogEventInfo logEvent)
{
var version = HttpContext.Current.Request.RequestContext.RouteData.Values["Version"];
builder.Append(version);
}
}
問題:HttpContext.Current
是NULL
我相信這是因爲我使用Async wrappers爲NLog
和記錄儀前幾個電話也是Async
。
記錄器在Ninject.Extensions.WebApi.UsageLogger中被稱爲Async的示例。在這一點上,HttpRequestMessage
有我們需要獲取版本的所有信息。
/// <summary>
/// Initializes a new instance of the <see cref="UsageHandler" /> class.
/// </summary>
public UsageHandler()
{
var kernel = new StandardKernel();
var logfactory = kernel.Get<ILoggerFactory>();
this.Log = logfactory.GetCurrentClassLogger();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var startTime = DateTime.Now;
// Log request
await request.Content.ReadAsStringAsync().ContinueWith(c =>
{
this.Log.Info("{0}: {1} called from {2}", request.Method, HttpUtility.UrlDecode(request.RequestUri.AbsoluteUri), ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress);
this.Log.Info("Content-Type: {0}, Content-Length: {1}", request.Content.Headers.ContentType != null ? request.Content.Headers.ContentType.MediaType : string.Empty, request.Content.Headers.ContentLength);
this.Log.Info("Accept-Encoding: {0}, Accept-Charset: {1}, Accept-Language: {2}", request.Headers.AcceptEncoding, request.Headers.AcceptCharset, request.Headers.AcceptLanguage);
if (!string.IsNullOrEmpty(c.Result))
{
if (this.MaxContentLength > 0 && c.Result.Length > this.MaxContentLength)
{
this.Log.Info("Data: {0}", HttpUtility.UrlDecode(c.Result).Substring(0, this.MaxContentLength - 1));
}
else
{
this.Log.Info("Data: {0}", HttpUtility.UrlDecode(c.Result));
}
}
});
var response = await base.SendAsync(request, cancellationToken);
// Log the error if it returned an error
if (!response.IsSuccessStatusCode)
{
this.Log.Error(response.Content.ReadAsStringAsync().Result);
}
// Log performance
this.Log.Info("Request processing time: " + DateTime.Now.Subtract(startTime).TotalSeconds + "s");
return response;
}
問題 什麼是使在通用方式VersionLayoutRenderer
工作的最佳方法?我可以添加MessageHandler並將HttpRequest綁定到某個異步作用域?如果是的話,任何指導方針將不勝感激,因爲我仍然習慣於Ninject
。
我暫時將版本信息直接添加到UsageHandler中的日誌調用中,但我真的很喜歡更通用的解決方案,我可以始終依賴日誌中的版本信息。
編輯:已更新的問題更加具體,包括更多細節。
您可以發佈代碼,您正在使用異步 – Jonathan
喬納森,請參閱更新的問題,我希望它包含您需要的所有信息,否則請提出。 –