[英]how do you read the body content of HttpResponse object in C#/ ASP.NET?
How do you read the content of an HttpResponse object in C# / ASP.net? 您如何在C#/ ASP.net中读取HttpResponse对象的内容?
I need to be able to read the body content as a JSON object, modify it, and then write it back to the response output stream. 我需要能够将主体内容作为JSON对象读取,进行修改,然后将其写回到响应输出流。 I want to make sure I don't lose what's already in the stream, thus I need to read from it first. 我想确保我不会丢失流中已经存在的内容,因此我需要先阅读它。
How do I do this? 我该怎么做呢?
You can use a Delegating handler 您可以使用委托处理程序
public class ContentHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) =>
{
HttpResponseMessage response = responseToCompleteTask.Result;
var YourContent = response.Content.ReadAsStreamAsync().Result;
response.Content = new CompressedContent(response.Content, acceptedEncoding);
return response;
},
TaskContinuationOptions.OnlyOnRanToCompletion);
}
}
Register your handler at WebApiConfig 在WebApiConfig注册您的处理程序
GlobalConfiguration.Configuration.MessageHandlers.Add(new ContentHandler());
You can edit your reponse content by extending the HttpContent Class. 您可以通过扩展HttpContent类来编辑响应内容。 For example to compress content 例如压缩内容
public class CompressedContent : HttpContent
{
private HttpContent originalContent;
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Stream editedStream = null;
if (encodingType == "gzip")
{
editedStream = new GZipStream(stream, CompressionMode.Compress, leaveOpen: true);
}
else if (encodingType == "deflate")
{
editedStream = new DeflateStream(stream, CompressionMode.Compress, leaveOpen: true);
}
return originalContent.CopyToAsync(editedStream).ContinueWith(tsk =>
{
if (editedStream != null)
{
editedStream.Dispose();
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.