ASP.NET Core修改/替代请求正文 [英] ASP.NET Core modify/substitute request body

查看:157
本文介绍了ASP.NET Core修改/替代请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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.

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

How can I modify/substitute Request.Body? I need to change property value of request body.

推荐答案

以请求正文为例,读取其内容,如果需要,请进行必要的更改根本,然后创建一个新的流来传递管道。一旦访问,就必须替换请求流。

Take the request body, read its content, make whatever changes are necessary if at all, then create a new stream to pass down the pipeline. Once accessed, the request stream has to be replaced.

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

这篇关于ASP.NET Core修改/替代请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆