我需要替换HttpContext.Request.Body。
我试图在中间件
中进行此操作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);
}
第一个问题是身体只能被读取一次,第二个问题是流是只读的并且不能被写入。 如何修改/替换request.body(我需要更改请求体的属性值)?
答案 0 :(得分:10)
获取请求正文,阅读其内容,根据需要进行必要的更改,然后创建新流以传递管道。访问后,必须替换请求流。
public async Task Invoke(HttpContext context) {
var request = context.Request;
if (request.Path.Value.Contains("DataSourceResult")) {
//get the request body and put it back for the downstream items to read
var stream = request.Body;// currently holds the original stream
var originalContent = new StreamReader(stream).ReadToEnd();
var notModified = true;
try {
var dataSource = JsonConvert.DeserializeObject<DataSourceRequest>(originalContent);
if (dataSource != null && dataSource.Take > 2000) {
dataSource.Take = 2000;
var json = JsonConvert.SerializeObject(dataSource);
//replace request stream to downstream handlers
var requestContent = new StringContent(json, Encoding.UTF8, "application/json");
stream = await requestContent.ReadAsStreamAsync();//modified stream
notModified = false;
}
} catch {
//No-op or log error
}
if (notModified) {
//put original data back for the downstream to read
var requestData = Encoding.UTF8.GetBytes(originalContent);
stream = new MemoryStream(requestData);
}
request.Body = stream;
}
await _next.Invoke(context);
}