[英].NET Core Web API - How to Get Response Information from ActionResult
I have a WebAPI Core endpoint method where I am using a in-house library (RequestLogManager) to save the request and response data from and incoming request.我有一个 WebAPI 核心端点方法,我使用内部库 (RequestLogManager) 来保存来自和传入请求的请求和响应数据。
Because I want to log the response code and body , I am storing the ActionResult in a variable that is returned at the end of the method (instead of returning from multiple locations in the method).因为我想记录响应代码和正文,所以我将 ActionResult 存储在方法结束时返回的变量中(而不是从方法中的多个位置返回)。 Example:
例子:
// 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;
}
At the end of my method, how can I get the value for the response code and body from ActionResult to log?在我的方法结束时,如何从 ActionResult 获取响应代码和正文的值以记录?
Unable to cast object of type 'Microsoft.AspNetCore.Mvc.NoContentResult' to type 'Microsoft.AspNetCore.Mvc.ObjectResult'
Unable to cast object of type 'Microsoft.AspNetCore.Mvc.NoContentResult' to type 'Microsoft.AspNetCore.Mvc.ObjectResult'
Middleware are the way to go to handle request and response logging.中间件是 go 处理请求和响应日志的方式。 You can your custom middleware and they can be hooked to the
HTTP
pipeline and you can perform the logging within the middleware implementations.您可以自定义中间件,它们可以连接到
HTTP
管道,您可以在中间件实现中执行日志记录。 This approach helps you do it globally.这种方法可以帮助您在全球范围内进行。
// 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
pipelineHTTP
管道This is pretty straightforward and done with the below statements of code.这非常简单,可以通过以下代码语句完成。
// Within the Configure() method of Startup.cs
app.UseMiddleware<ResponseLoggingMiddleware>();
app.UseMiddleware<RequestLoggingMiddleware>();
The order in which you are hooking up the middleware matters here.连接中间件的顺序在这里很重要。 More information on middleware ordering and middleware in general here
有关中间件排序和一般中间件的更多信息,请点击此处
Update:更新:
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;
}
}
This attribute can now be added to your action method inside your controller wherever required as shown below.现在可以将此属性添加到 controller 内的操作方法中,只要需要,如下所示。
[HttpGet]
[LoggingAttribute]
public ActionResult<IEnumerable<string>> Get()
{
// ...other code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.