Asp.net-Web-Api
從 ExceptionLogger 引用動作參數
我想利用新方法來全域記錄錯誤。我編寫了一個繼承
ExceptionLogger和覆蓋該Log()方法的類。然後將其註冊為替代品。public class TraceExceptionLogger : ExceptionLogger { public async override void Log(ExceptionLoggerContext context) { // This is always empty string var content = await context.Request.Content.ReadAsStringAsync(); // This is almost always null var actionContext = context.ExceptionContext.ActionContext; } }我可以探勘
ExceptionLoggerContext對象的屬性來獲得我需要的幾乎所有東西,除了動作參數。確實有一個ActionContext屬性,但我只看到它為空,這個 wiki 頁面聲明ActionContext並且ControllerContext幾乎總是為空。另外,我無法獲取內容流,因為它的流在到達我的記錄器之前已經被讀取。因此,我無法從請求的內容中獲取任何已發布的 json。
HttpContext.Current有沒有辦法從或以其他方式獲取發布的數據?
好的,看起來我可以通過讀取 Request 對像上的 InputStream 從 HttpContext 獲取正文,如下所示:
string bodyText = string.Empty; using (var sr = new StreamReader(HttpContext.Current.Request.InputStream)) { sr.BaseStream.Seek(0, SeekOrigin.Begin); bodyText = sr.ReadToEnd(); }到目前為止,這段程式碼已經成功地獲取了我發布的 json 數據。
這是動作參數以供將來參考
public class HomeController : ApiController { public string Get(string id, [FromHeader] Whoever whoever) { public string Post(Whatever whatever) { var args = ((ApiController) context.ExceptionContext .ControllerContext.Controller)).ActionContext.ActionArguments if (args.ContainsKey("whatever")) { var whatever = (Whatever)args["whatever"];