gpt4 book ai didi

c# - ASP.NET Core 修改/替换请求体

转载 作者:太空狗 更新时间:2023-10-29 17:42:59 25 4
gpt4 key购买 nike

我想对 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只能读一次,其次流是只读的,不能写。

如何修改/替换 Request.Body?我需要更改请求正文的属性值。

最佳答案

获取请求正文,读取其内容,进行任何必要的更改(如果有的话),然后创建一个新流以向下传递管道。一旦访问,就必须替换请求流。

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);
}

关于c# - ASP.NET Core 修改/替换请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44498802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com