1.创建中件间
public class RequestResponseMiddleware { private readonly RequestDelegate _next; public RequestResponseMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { #region 修改请求的body var requestBodyStream = new MemoryStream();//创建一个流 //设置当前流的位置未0 requestBodyStream.Seek(0, SeekOrigin.Begin);//设置从0开始读取 //这里ReadToEnd执行完毕后requestBodyStream流的位置会从0到最后位置(即request.ContentLength) var RequestBody = new StreamReader(context.Request.Body).ReadToEnd();//读取body //需要将流位置重置偏移到0,不然后续的action读取不到request.Content的值 requestBodyStream.Seek(0, SeekOrigin.Begin); byte[] content1 = Encoding.UTF8.GetBytes(RequestBody.Replace("ceo", "CEO"));//替换字符串并且字符串转换成字节 requestBodyStream.Seek(0, SeekOrigin.Begin); requestBodyStream.Write(content1, 0, content1.Length);//把修改写入流中 context.Request.Body = requestBodyStream;//把修改后的内容赋值给请求body context.Request.Body.Seek(0, SeekOrigin.Begin); #endregion #region 返回数据 using (var ms = new MemoryStream())//创建一个流 { var orgBodyStream = context.Response.Body;//获取body内容 context.Response.Body = ms;//把创建的流赋值给body await _next(context);//执行下一个内容 using (var sr = new StreamReader(ms))// { ms.Seek(0, SeekOrigin.Begin); if (sr.ReadToEnd().Contains("/uploadfiles/")) { //获取appsettings.json中的 var appsettingsjson = JObject.Parse(System.IO.File.ReadAllText("appsettings.json")); var fileUrlConfig = (JObject)appsettingsjson["FileUrlConfig"]; var url = fileUrlConfig.Property("Url").Value.ToString(); ms.Seek(0, SeekOrigin.Begin); byte[] content = Encoding.UTF8.GetBytes(sr.ReadToEnd().Replace("/uploadfiles", url + "/uploadfiles"));//字符串转换成字节 ms.Seek(0, SeekOrigin.Begin); ms.Write(content, 0, content.Length); } ms.Seek(0, SeekOrigin.Begin); await ms.CopyToAsync(orgBodyStream); } } #endregion } }
2.在startup启动项中调用中件间(必须是请求之前调用该中件间)
app.UseMiddleware<RequestResponseMiddleware>();