Я хочу получить тело запроса Http в ядре .net, я использовал этот код:
using (var reader
= new StreamReader(req.Body, Encoding.UTF8))
{
bodyStr = reader.ReadToEnd();
}
req.Body.Position = 0
Но я получил эту ошибку:
System.ObjectDisposedException: невозможно получить доступ к удаленному объекту. Имя объекта: FileBufferingReadStream.
Ошибка возникает после оператора using строки
Как получить тело запроса Http в ядре .NET? и как исправить эту ошибку?
5
rayan periyera
23 Окт 2018 в 13:26
2 ответа
Лучший ответ
Используя этот метод расширения, чтобы получить тело запроса http:
public static string GetRawBodyString(this HttpContext httpContext, Encoding encoding)
{
var body = "";
if (httpContext.Request.ContentLength == null || !(httpContext.Request.ContentLength > 0) ||
!httpContext.Request.Body.CanSeek) return body;
httpContext.Request.EnableRewind();
httpContext.Request.Body.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(httpContext.Request.Body, encoding, true, 1024, true))
{
body = reader.ReadToEnd();
}
httpContext.Request.Body.Position = 0;
return body;
}
Важно то, что HttpRequest.Body - это тип Stream. И когда StreamReader удаляется, HttpRequest.Body также удаляется.
У меня была эта проблема, пока я не нашел эту ссылку ниже в github: См. Ссылку ниже и метод GetBody
6
amirhamini
23 Окт 2018 в 10:50
Принятый ответ у меня не сработал, но тело читал дважды.
public static string ReadRequestBody(this HttpRequest request, Encoding encoding)
{
var body = "";
request.EnableRewind();
if (request.ContentLength == null ||
!(request.ContentLength > 0) ||
!request.Body.CanSeek)
{
return body;
}
request.Body.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(request.Body, encoding, true, 1024, true))
{
body = reader.ReadToEnd();
}
//Reset the stream so data is not lost
request.Body.Position = 0;
return body;
}
0
eddyP23
2 Июл 2019 в 08:00