gpt4 book ai didi

asp.net-mvc - ASP.NET Web API 记录入站请求内容

转载 作者:行者123 更新时间:2023-12-01 21:30:46 24 4
gpt4 key购买 nike

我正在尝试注销 Web API 请求内容 – 即 json 字符串。我实现了一个 ITraceWriter 类 ( example ) 并对其进行配置,以便 Web API 在管道中调用它。但是,如果我读取 request.Content 或复制到流中进行读取,则该方法将无法使用该方法,从而导致空模型。 This post稍微谈一下这个问题。有人有注销入站 Web API 请求内容的经验并知道最好的方法是什么吗?

谢谢

更新A

我创建了一个简单的示例 Web API 项目来排除项目​​中的任何内容,但我仍然看到模型因日志记录而将为空。我只是通过 Fidder 发布来连续测试几次,然后看到我的模型为空。设置断点后,它可能会起作用,这就是为什么我认为存在同步/计时问题。关于如何让它发挥作用有什么想法吗?

标题:

User-Agent: Fiddler
Host: localhost:56824
Content-Type: application/json
Content-Length: 22

正文:

{
"A":1,"B":"test"
}

代码如下:

Controller :

public class ValuesController : ApiController
{
[HttpPost]
public void Post(ValuesModel model)
{
if (model == null)
{
Debug.WriteLine("model was null!");
}
else
{
Debug.WriteLine("model was NOT null!");
}
}
}

型号:

public class ValuesModel
{
public int A { get; set; }
public string B { get; set; }
}

记录器:

public class APITraceLogger : DelegatingHandler
{
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (request.Content != null)
{
// This can cause model to be null
request.Content.ReadAsStringAsync().ContinueWith(s =>
{
string requestText = s.Result;
Debug.WriteLine(requestText);
});

// and so can this
//request.Content.ReadAsByteArrayAsync()
// .ContinueWith((task) =>
// {
// string requestText = System.Text.UTF8Encoding.UTF8.GetString(task.Result);
// Debug.WriteLine(requestText);
// });
}
// Execute the request, this does not block
var response = base.SendAsync(request, cancellationToken);

// TODO:
// Once the response is processed asynchronously, log the response data
// to the database


return response;
}


}

在 WebApiConfig 类中连接记录器:

config.MessageHandlers.Add(new APITraceLogger());

更新B

如果我将记录器更改为以下代码,添加等待、异步并返回结果,它似乎现在可以工作了。看起来像是我在异步代码中不理解的东西,或者确实是一个计时问题或其他问题。

public class APITraceLogger : DelegatingHandler
{
protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (request.Content != null)
{

// This does seem to work - is it because it is synchronous? Is this a potential problem?
var requestText = await request.Content.ReadAsStringAsync();
Debug.WriteLine(requestText);
}
// Execute the request, this does not block
var response = base.SendAsync(request, cancellationToken);

// TODO:
// Once the response is processed asynchronously, log the response data
// to the database


return response.Result;
}


}

最佳答案

正如 Filip 在那篇文章中提到的那样,ReadAsStringAsync 或 ReadAsByteArrayAsync 方法会在内部缓冲请求内容。这意味着,即使传入请求的流类型是非缓冲流,您也可以安全地在消息处理程序中执行 ReadAsStringAsync/ReadAsByteArrayAsync,并且还期望模型绑定(bind)正常工作。

默认情况下,请求的流在网络主机和自主机情况下都会被缓冲。但是,如果您想检查即使在非缓冲模式下使用 ReadAsStringAsync/ReadAsByteArrayAsync 和模型出价是否也能正常工作,您可以执行以下操作来强制使用非缓冲模式:

public class CustomBufferPolicySelector : WebHostBufferPolicySelector
{
public override bool UseBufferedInputStream(object hostContext)
{
//NOTE: by default, the request stream is always in buffered mode.
//return base.UseBufferedInputStream(hostContext);

return false;
}
}

config.Services.Replace(typeof(IHostBufferPolicySelector), new CustomBufferPolicySelector());

仅供引用...上述策略选择器目前仅适用于 Web 主机。如果您想在 SelfHost 中进行类似的测试,请执行以下操作:

//NOTE: by default, the transfer mode is TransferMode.Buffered
config.TransferMode = System.ServiceModel.TransferMode.StreamedRequest;

上述帖子更新 B 后:

您可以像下面这样修改您的处理程序:

public class LoggingHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Content != null)
{
string requestContent = await request.Content.ReadAsStringAsync();
}

HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

if (response.Content != null)
{
string responseContent = await response.Content.ReadAsStringAsync();
}

return response;
}
}

关于asp.net-mvc - ASP.NET Web API 记录入站请求内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15508801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com