Web API 请求内容为空

本文关键字:API 请求 Web | 更新日期: 2023-09-27 18:32:20

我有一个DemissionatingHandler实现来记录请求/响应内容:

public class RequestAndResponseLoggerDelegatingHandler : DelegatingHandler
{
    public IDataAccess Data { get; set; }
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var started = DateTime.UtcNow;
        var response = await base.SendAsync(request, cancellationToken);
        await Log(started, request, response);
        return response;
    }
    private async Task Log(DateTime start, HttpRequestMessage request, HttpResponseMessage response)
    {
        var finished = DateTime.UtcNow;
        var requestContent = await request.Content.ReadAsStringAsync();
        var responseContent = await response.Content.ReadAsStringAsync();
        var info = new ApiLogEntry(start, finished, requestContent, responseContent, request, response);
        Data.Log(info);
    }
}

但出于某种原因,requestContent是空的。 request.Content.Length确认有内容,只是没有被提取。

有什么想法吗?

Web API 请求内容为空

读取请求正文流并将其绑定到参数中,作为绑定的结果,流已定位到末尾。这就是为什么它是空的。如果你在request.Content.ReadAsStringAsync()之前寻求开始,它应该有效。取而代之的是,您可以在绑定发生之前先读取请求正文,例如这样的事情。

public class RequestAndResponseLoggerDelegatingHandler : DelegatingHandler
{
    public IDataAccess Data { get; set; }
    protected override async Task<HttpResponseMessage> SendAsync(
                            HttpRequestMessage request, 
                                 CancellationToken cancellationToken)
    {
        var started = DateTime.UtcNow;
        var requestContent = await request.Content.ReadAsStringAsync();
        var response = await base.SendAsync(request, cancellationToken);
        var responseContent = await response.Content.ReadAsStringAsync();
        await Log(started, request, response, requestContent, responseContent);
        return response;
    }
    private async Task Log(DateTime start, HttpRequestMessage request, 
                             HttpResponseMessage response, string requestContent, 
                                string responseContent)
    {
        var finished = DateTime.UtcNow;           
        var info = new ApiLogEntry(start, finished, requestContent, responseContent, 
                                        request, response);
        Data.Log(info);
    }
}