WebAPI 讀取Request的InputStream

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.