[英].NET Core Web API - How to Get Response Information from ActionResult
我有一個 WebAPI 核心端點方法,我使用內部庫 (RequestLogManager) 來保存來自和傳入請求的請求和響應數據。
因為我想記錄響應代碼和正文,所以我將 ActionResult 存儲在方法結束時返回的變量中(而不是從方法中的多個位置返回)。 例子:
// This is a contrived method to illustrate the issue.
[Route("test/actionresult/{testParam:int}")]
[HttpGet]
public async Task<ActionResult> GetTestActionResult(int testParam)
{
ActionResult actionResult = Ok(); // Default
// Log Incoming Request
int requestlogid = await RequestLogManager.LogIncomingRequestAsync("API - GetTestActionResult", Request);
switch (testParam)
{
case 204:
actionResult = NoContent();
break;
case 404:
actionResult = NotFound();
break;
case 500:
actionResult = StatusCode(StatusCodes.Status500InternalServerError, "An Error Occurred!");
break;
default:
break;
}
// Log Outgoing Response
RequestLogManager.LogResponseForRequestNoWait(requestlogid, ??? ResponseBody ???, ??? ResponseCode ???);
return actionResult;
}
在我的方法結束時,如何從 ActionResult 獲取響應代碼和正文的值以記錄?
Unable to cast object of type 'Microsoft.AspNetCore.Mvc.NoContentResult' to type 'Microsoft.AspNetCore.Mvc.ObjectResult'
中間件是 go 處理請求和響應日志的方式。 您可以自定義中間件,它們可以連接到HTTP
管道,您可以在中間件實現中執行日志記錄。 這種方法可以幫助您在全球范圍內進行。
// Request Logging middleware
public class RequestLoggingMiddleware
{
private RequestDelegate _next;
public RequestLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Logic to log your request. Can be accessed via "context.Request"
await _next.Invoke(context);
}
}
// Response Logging Middleware
public class ResponseLoggingMiddleware
{
private RequestDelegate _next;
public ResponseLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// observe the Invoke() method being called first
await _next.Invoke(context)
// This is where your logging logic goes. For eg., you can capture 404 as below
if(context.Response.StatusCode == 404)
{
// log the 404 and do whatever you want to do on a 404 here.
}
}
}
HTTP
管道這非常簡單,可以通過以下代碼語句完成。
// Within the Configure() method of Startup.cs
app.UseMiddleware<ResponseLoggingMiddleware>();
app.UseMiddleware<RequestLoggingMiddleware>();
連接中間件的順序在這里很重要。 有關中間件排序和一般中間件的更多信息,請點擊此處
更新:
public class LoggingAttribute : Attribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
// This method is called just right after the completion of the
// execution of the action method. Status Code can be obtained as shown below
// response logging based on status code goes here.
var result = context.Result;
var response = context.HttpContext.Response.StatusCode;
}
public void OnActionExecuting(ActionExecutingContext context)
{
// This method is called before the action method is invoked.
// Access the request using context.HttpContext.Request
// and include the logging logic where
var request = context.HttpContext.Request;
}
}
現在可以將此屬性添加到 controller 內的操作方法中,只要需要,如下所示。
[HttpGet]
[LoggingAttribute]
public ActionResult<IEnumerable<string>> Get()
{
// ...other code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.