c# – ASP NET核心修改/替换请求体

前端之家收集整理的这篇文章主要介绍了c# – ASP NET核心修改/替换请求体前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要替换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,bytesToWrite.Length);
            }
            else
            {
                var bytesToWrite = originalBody.AsByteArray();
                await context.Request.Body.WriteAsync(bytesToWrite,bytesToWrite.Length);
            }
        }

        await _next.Invoke(context);
    }

第一个问题是主体只能读取一次,第二个问题是流是只读的,不能写入.
如何修改/替换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);
}
原文链接:https://www.f2er.com/csharp/244088.html

猜你在找的C#相关文章