標籤:style blog http ar io color os sp on
最近的項目有一個需求,就是在每個Request開始的時候,讀取每個Request的body中的內容,做些Logging,然後再根據Route分別處理。
大概是這個樣子
[HttpPost][Route("api/{id}/add")]public HttpResponseMessage Add(string id, [FromBody]string body){ ...}
為了在每個Request開始的時候做logging,只要在Global.asax.cs的Application_BeginRequst中做相應處理
protected void Application_BeginRequest(object sender, EventArgs e){ var request = ((HttpApplication)sender).Request; string content; using (var reader = new StreamReader(request.InputStream)) { content = reader.ReadToEnd(); } ...}
這樣雖然可以拿到request.InputStream中的內容,但是卻進不去Add函數了,原因是WebAPI不能再從request.InputStream讀取body的值。
即使我在Application_BeginRequest中把request.InputStream.Position = 0,還是不行。
造成這種情況可能的原因是,StreamReader在Dispose的時候,把request.InputStream也Dispose了。
解決辦法
protected void Application_BeginRequest(object sender, EventArgs e){ var request = ((HttpApplication)sender).Request; string content; var bytes = new byte[request.InputStream.Length]; request.InputStream.Read(bytes, 0, bytes.Length); request.InputStream.Position = 0; string content = Encoding.UTF8.GetString(bytes); ...}
WebAPI 讀取Request的InputStream