I want to do a substitution on HttpContext.Request.Body
.
I've tried to do it inside a middleware:
public async Task Invoke(HttpContext context)
{
if (context.Request.Path.Value.Contains("DataSourceResult"))
{
var originalBody = new StreamReader(context.Request.Body).ReadToEnd();
DataSourceRequest dataSource = null;
try
{
dataSource = JsonConvert.DeserializeObject<DataSourceRequest>(originalBody);
} catch
{
await _next.Invoke(context);
}
if (dataSource != null && dataSource.Take > 2000)
{
dataSource.Take = 2000;
var bytesToWrite = dataSource.AsByteArray();
await context.Request.Body.WriteAsync(bytesToWrite, 0, bytesToWrite.Length);
}
else
{
var bytesToWrite = originalBody.AsByteArray();
await context.Request.Body.WriteAsync(bytesToWrite, 0, bytesToWrite.Length);
}
}
await _next.Invoke(context);
}
The first problem is that the body can be read only once, and secondly, the stream is read-only and can't be written to.
How can I modify/substitute Request.Body
? I need to change property value of request body.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…