ASP NET Core修改/替代请求正文

编程入门 行业动态 更新时间:2024-10-24 18:24:48
本文介绍了ASP NET Core修改/替代请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要替换HttpContext.Request.Body。

I need to do the substitution of 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); }

第一个问题是正文只能被读取一次,第二个是该流是只读的,不能被写入。 如何修改/替换request.body(我需要更改请求正文的属性值)?

First problem is that the body can be read only once, and second one is that the stream is read only and can't be written. How can I modify/substitute request.body(I need to change property value of request body)?

推荐答案

获取请求正文,读取其内容,进行必要的更改,然后创建新的流以传递到管道中。一旦访问,请求流就必须替换。

Take the request body, read it's content, make what ever changes are necessary if at all, then create a new stream to pass down the pipeline. Once accessed, the request stream has to be replace.

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修改/替代请求正文

本文发布于:2023-11-03 14:51:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555403.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正文   ASP   NET   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!