C# 记录ASP.NET Web API请求
我编写这个简单的类是为了记录请求属性:C# 记录ASP.NET Web API请求,c#,asp.net,asp.net-web-api,async-await,C#,Asp.net,Asp.net Web Api,Async Await,我编写这个简单的类是为了记录请求属性: public class Logger : ActionFilterAttribute { private string logPath; public Logger() { System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebCo
public class Logger : ActionFilterAttribute
{
private string logPath;
public Logger()
{
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~\\web.config");
logPath = rootWebConfig.AppSettings.Settings["logPath"].Value;
}
public override async System.Threading.Tasks.Task OnActionExecutingAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
{
await WriteLogAsync(actionContext);
}
private async System.Threading.Tasks.Task WriteLogAsync(System.Web.Http.Controllers.HttpActionContext actionContext)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPath, true))
{
await file.WriteLineAsync("==========================");
await file.WriteLineAsync(DateTime.Now.ToString());
await file.WriteLineAsync("URL: " + actionContext.Request.RequestUri);
await file.WriteLineAsync("Headers: " + actionContext.Request.Headers);
await file.WriteLineAsync("Content-type: " + actionContext.Request.Content.Headers.ContentType);
await file.WriteLineAsync("Content: " + (await actionContext.Request.Content.ReadAsStringAsync())); **// Content is always empty**
await file.WriteLineAsync("==========================");
}
}
}
问题在标记行中。内容始终是空字符串,尽管我发送的数组如下:[118119120122123,24,19,20,21,22,23124]
我在这里缺少什么?您的
请求
流已被WebApi格式化程序使用。看:谢谢。您的链接很有用。您可能希望使用单个写入操作。太多的等待将影响性能。@PauloMorgado它取决于AutoFlush
的值,对吗?否。对于每个wait
关键字,将创建一个任务。而且编译器生成的状态机也会更大。使用反射工具(.netreflector、ILSpy、JustDecompile)查看生成的代码。