【发布时间】:2017-11-13 21:24:58
【问题描述】:
我想对 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);
}
第一个问题是body只能读取一次,其次stream是只读的,不能写入。
如何修改/替换Request.Body?我需要更改请求正文的属性值。
【问题讨论】:
标签: c# asp.net-core .net-core asp.net-core-middleware