我有一個名爲Log的屬性,它嘗試將請求和響應的內容記錄到文本文件中。我已經把它放在我的控制器上以涵蓋所有的操作。在LogAttribute中,我以字符串形式讀取內容(ReadAsStringAsync),所以我不會丟失請求主體。Web Api請求內容在操作中爲空過濾器
public class LogAttribute : ActionFilterAttribute
{
// ..
public override void OnActionExecuting(HttpActionContext actionContext)
{
// stuff goes here
var content = actionContext.Request.Content.ReadAsStringAsync().Result;
// content is always empty because request body is cleared
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// other stuff goes here
var content = actionContext.Request.Content.ReadAsStringAsync().Result;
// content is always empty because request body is cleared
}
// ..
}
另一方面,我把FromBody屬性放在我的動作參數類之前,以利用它的好處。
[Log]
public class SomethingController
{
public HttpResponseMessage Foo([FromBody] myModel)
{
// something
}
}
問題是內容在ActionExecuting或ActionExecuted中總是爲空。
我認爲這是因爲FromBody在我的Log屬性之前運行,不像它們在代碼中的順序。再次,我認爲它是因爲根據動作參數(路由處理)爲請求找到最佳動作/控制器匹配。之後,我的請求主體被清除,因爲請求主體在WebApi中是非緩衝的。
我想知道是否有任何方法來改變FromBody屬性和我的Log屬性的運行時間順序?或其他解決問題的東西!我應該提到,我不想刪除FromBody並使用HttpRequestMessage而不是我的Model或類似的東西。
除此之外,您的異步處理是錯誤的。使用.Result是危險的,你應該避免,如果possilbe。而是重寫允許您等待的OnActionExecutingAsync方法。 –
@盧卡斯克其實這是寫的只是爲了解釋我的問題。但你是對的。 –