gpt4 book ai didi

c# - 阅读HttpContent的前n个字符

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:27:23 25 4
gpt4 key购买 nike

我想在visual c web api程序中记录有关httprequestmessage响应的信息。我想使用这样的消息处理程序(从delegatinghandler继承):

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
{
// log request.Method & request.RequestUri
var result = await base.SendAsync(request, cancellationToken);
// log first 100 chars of result.Content
return result
}

问题是 result.Content有时会很大,所以我想限制它只打印前n个字符(大约50个)。
我试过的:
toString()SubString将整个内容复制到字符串中。这正是我想要的,但是把大量的字符串读入内存,然后只使用前几个字符似乎是浪费——我觉得一定有更好的方法。
各种各样的解决方案,从互联网上阅读的字符,但删除他们从流。我需要把所有的信息都发回去。

最佳答案

通过这个,您可以从流中复制所需的信息,并将响应传递到要去的地方。

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {
// log request.Method & request.RequestUri
var response = await base.SendAsync(request, cancellationToken);
// log first 100 chars of response.Content
var N = 100;
var first_100_Chars = await ReadFirstNCharsOfHttpContent(response.Content, N);

return response;
}

private static async Task<string> ReadFirstNCharsOfHttpContent(HttpContent httpContent, int N = 100) {
//get the content Stream
var contentStream = await httpContent.ReadAsStreamAsync().ConfigureAwait(false);
//How big is it
var streamLength = contentStream.Length;
// Get the size of the buffer to be read
var bufferSize = (int)(streamLength > N ? N : (N > streamLength ? streamLength : N));
var ms = new System.IO.MemoryStream(bufferSize);
//copy only the needed length
await contentStream.CopyToAsync(ms, bufferSize);

// The StreamReader will read from the current
// position of the MemoryStream which is currently
// set at the end of the data we just copied to it.

// We need to set the position to 0 in order to read
// from the beginning.
ms.Position = 0;
//reset content position just to be safe.
contentStream.Position = 0;

var sr = new System.IO.StreamReader(ms);
var logString = sr.ReadToEnd();

return logString;
}

关于c# - 阅读HttpContent的前n个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35882883/

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