簡體   English   中英

.NET Core Web API - 如何從 ActionResult 獲取響應信息

[英].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 獲取響應代碼和正文的值以記錄?

  • 我嘗試使用 Response.Body 和 Response.StatusCode,但它們總是“”和 200(我推測是因為我使用的是 ActionResult 而不是實際創建 HttpResponse)。
  • 我嘗試將 ActionResult 轉換為 ObjectResult - ObjectResult 在屬性 StatusCode 和 Value 中確實有這些 - 但這會導致錯誤消息: 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
}

從 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> 如何在 .NET 核心 5 Web ZDB974238714CA8DE634A7CE1D083A1 項目中自動格式化 API 響應? ASP.NET Core中如何獲取ActionResult StatusCode 如何從 ASP.NET 核心 web 應用程序中獲取 JSON 信息 如何從 ASP.NET Core Web API 向客戶端發送 JSON 響應? 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 自定義操作結果 Controller方法返回ActionResult的原因是什么? (ASP.NET Core Web API) .Net 核心 Web API 未記錄 204 響應 在高圖中顯示.Net核心Web API響應
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM