Skip to content

Commit

Permalink
🎨 优化响应流读取,兼容MemoryStream
Browse files Browse the repository at this point in the history
  • Loading branch information
LemonNoCry committed Nov 11, 2023
1 parent afb9a0d commit c85f51a
Showing 1 changed file with 24 additions and 24 deletions.
48 changes: 24 additions & 24 deletions Blog.Core.Common/Extensions/HttpResponseExceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,29 @@ namespace Blog.Core.Common.Extensions;

public static class HttpResponseExceptions
{
public static string GetResponseBody(this HttpResponse response)
{
if (response is null)
{
return default;
}
public static string GetResponseBody(this HttpResponse response)
{
if (response is null)
{
return string.Empty;
}

if (response.Body is FluentHttpResponseStream responseBody)
{
response.Body.Position = 0;
//不关闭底层流
using StreamReader stream = new StreamReader(responseBody, leaveOpen: true);
string body = stream.ReadToEnd();
response.Body.Position = 0;
return body;
}
else
{
//原始HttpResponseStream 无法读取
//实际上只是个包装类,内部使用了HttpResponsePipeWriter write
throw new ApplicationException("The response body is not a FluentHttpResponseStream");
}
return default;
}
//原始HttpResponseStream 无法读取
//实际上只是个包装类,内部使用了HttpResponsePipeWriter write
switch (response.Body)
{
case FluentHttpResponseStream:
case MemoryStream:
{
response.Body.Position = 0;
using var stream = new StreamReader(response.Body, leaveOpen: true);
var body = stream.ReadToEnd();
response.Body.Position = 0;
return body;
}
default:
// throw new ApplicationException("The response body is not a FluentHttpResponseStream");
return string.Empty;
}
}
}

0 comments on commit c85f51a

Please sign in to comment.