在 asp.net 核心中间件中替换 Request/Response 主体

Replacing Request/Response Body in asp.net core middleware

我想替换中间件中的 request/response 正文。假设如果客户端发送 Hello,我想将其更改为 Hola 并且响应类似。我找到了有效但不符合我要求的代码。我的问题是为什么这个有效而另一个无效。实际上是相同的代码。

工作代码

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
       {
            var request = context.Request;
            var stream = request.Body;// currently holds the original stream                    
            var originalReader = new StreamReader(stream);
            var originalContent = await originalReader.ReadToEndAsync();
            var notModified = true;
            try
            {

                if (originalContent != null)
                {
                    //Master is some model name
                    var modifiedData = new Master() { Id = "Changed in Middleware", Email = "Changed" };
                    var json = JsonConvert.SerializeObject(modifiedData);
                    //json variable is just a string here
                    //modified stream
                    var requestData = Encoding.UTF8.GetBytes(json);
                    stream = new MemoryStream(requestData);
                    notModified = false;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            if (notModified)
            {
                //putting original data
                var requestData = Encoding.UTF8.GetBytes(originalContent);
                stream = new MemoryStream(requestData);
            }

            request.Body = stream;
            
            await next(context);
        }

代码不工作但是我的要求

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
       {
            var request = context.Request;
            var stream = request.Body;// currently holds the original stream                    
            var originalReader = new StreamReader(stream);
            var originalContent = await originalReader.ReadToEndAsync();
            var notModified = true;
            try
            {

                if (originalContent != null)
                {
                    var json = "This is just a string as deserializing returns string";
                    //modified stream
                    var requestData = Encoding.UTF8.GetBytes(json);
                    stream = new MemoryStream(requestData);
                    notModified = false;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            if (notModified)
            {
                //putting original data
                var requestData = Encoding.UTF8.GetBytes(originalContent);
                stream = new MemoryStream(requestData);
            }

            request.Body = stream;
            
            await next(context);
        }

因此 工作代码 将更改传递给控制器​​,并具有值 Id ="Changed in middlware"Email = "已更改" 无效代码 未传递任何内容...在控制器中,参数为 null 而不是 "这只是反序列化 returns string" 值的字符串。我知道这不是什么神奇的事情发生。我错过了什么吗?

您需要将字符串转换为 jsontype.Try 才能像这样更改您的代码:

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
   {
        var request = context.Request;
        var stream = request.Body;// currently holds the original stream                    
        var originalReader = new StreamReader(stream);
        var originalContent = await originalReader.ReadToEndAsync();
        var notModified = true;
        try
        {

            if (originalContent != null)
            {
                var str = "This is just a string as deserializing returns string";
                //convert string to jsontype
                var json = JsonConvert.SerializeObject(str);
                //modified stream
                var requestData = Encoding.UTF8.GetBytes(json);
                stream = new MemoryStream(requestData);
                notModified = false;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        if (notModified)
        {
            //putting original data
            var requestData = Encoding.UTF8.GetBytes(originalContent);
            stream = new MemoryStream(requestData);
        }

        request.Body = stream;
        
        await next(context);
    }

TestRequestBody 操作:

public IActionResult TestRequestBody([FromBody] string s)
        {

            return Ok();
        }

结果: