简体   繁体   English

.NET Core Web API - 如何从 ActionResult 获取响应信息

[英].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 获取响应代码和正文的值以记录?

  • I tried using Response.Body and Response.StatusCode, but those are always "" and 200 (I presume because I'm using ActionResult and not actually creating an HttpResponse).我尝试使用 Response.Body 和 Response.StatusCode,但它们总是“”和 200(我推测是因为我使用的是 ActionResult 而不是实际创建 HttpResponse)。
  • I tried casting ActionResult to ObjectResult - ObjectResult does have those in properties StatusCode and Value - but that results in an error message: Unable to cast object of type 'Microsoft.AspNetCore.Mvc.NoContentResult' to type 'Microsoft.AspNetCore.Mvc.ObjectResult'我尝试将 ActionResult 转换为 ObjectResult - ObjectResult 在属性 StatusCode 和 Value 中确实有这些 - 但这会导致错误消息: 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.这种方法可以帮助您在全球范围内进行。

Creating middleware for your intercepting your requests and responses创建中间件以拦截请求和响应

// 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.
        }
    }
}

Hooking up the middleware to HTTP pipeline将中间件连接到HTTP管道

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:更新:

Creating custom attribute to handle logging at endpoint level创建自定义属性以处理端点级别的日志记录

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
}

从 ActionResult 中获取值<object>在 ASP.Net Core API 方法中<div id="text_translate"><p>我尝试从 ASP.NET 核心 API 方法中的ActionResult&lt;object&gt;获取值。</p><p> API 有不同的 controller。 我尝试使用 controller A 中的 controller B 中的方法返回结果值。 我从 controller B 得到一个ActionResult object。我可以在ResultObject中使用调试器查看该值,但是如何访问其中的结果值?</p><pre> public ActionResult&lt;object&gt; getSourceRowCounter(string sourcePath) //Method from Controller A { var result = ControllerB.GetValue($"{sourcePath}.{rowCounterVariableName}"); var result2 = result.Value; //null var result3 = result.Result; //typ: {Microsoft.AspNetCore.Mvc.OkObjectResult} &lt;-see Value=4 in it with Debugger //var result4 = result3.Value; //Error?. //var result5 = result3;Content? //Error.? //var result6 = result3????;?; //How can i get the Value = 4? return Ok(result); //should only return value 4 and not the whole object }</pre> <p><img src="https://i.stack.imgur.com/4Lppi.jpg" alt="在此处输入图像描述"></p></div></object> - Get a Value from ActionResult<object> in a ASP.Net Core API Method

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 ActionResult 中获取值<object>在 ASP.Net Core API 方法中<div id="text_translate"><p>我尝试从 ASP.NET 核心 API 方法中的ActionResult&lt;object&gt;获取值。</p><p> API 有不同的 controller。 我尝试使用 controller A 中的 controller B 中的方法返回结果值。 我从 controller B 得到一个ActionResult object。我可以在ResultObject中使用调试器查看该值,但是如何访问其中的结果值?</p><pre> public ActionResult&lt;object&gt; getSourceRowCounter(string sourcePath) //Method from Controller A { var result = ControllerB.GetValue($"{sourcePath}.{rowCounterVariableName}"); var result2 = result.Value; //null var result3 = result.Result; //typ: {Microsoft.AspNetCore.Mvc.OkObjectResult} &lt;-see Value=4 in it with Debugger //var result4 = result3.Value; //Error?. //var result5 = result3;Content? //Error.? //var result6 = result3????;?; //How can i get the Value = 4? return Ok(result); //should only return value 4 and not the whole object }</pre> <p><img src="https://i.stack.imgur.com/4Lppi.jpg" alt="在此处输入图像描述"></p></div></object> - Get a Value from ActionResult<object> in a ASP.Net Core API Method 如何在 .NET 核心 5 Web ZDB974238714CA8DE634A7CE1D083A1 项目中自动格式化 API 响应? - How to autoformat API response in .NET core 5 Web API project? ASP.NET Core中如何获取ActionResult StatusCode - How to get ActionResult StatusCode in ASP.NET Core 如何从 ASP.NET 核心 web 应用程序中获取 JSON 信息 - How to get JSON information from ASP.NET core web app using JavaScript 如何从 ASP.NET Core Web API 向客户端发送 JSON 响应? - How can I send JSON response to client from ASP.NET Core Web API? Sending class data as JSON array format for GET request Response in ASP.Net Dot Core Web API ( GET response data from Web API) - Sending class data as JSON array format for GET request Response in ASP.Net Dot Core Web API ( GET response data from Web API) Asp.net 5 web api 自定义操作结果 - Asp.net 5 web api Custom ActionResult Controller方法返回ActionResult的原因是什么? (ASP.NET Core Web API) - What's the reason why Controller methods return ActionResult? (ASP.NET Core Web API) .Net 核心 Web API 未记录 204 响应 - .Net Core Web API undocumented 204 Response 在高图中显示.Net核心Web API响应 - show .Net core web API response in highcharts
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM