public class RequestMiddleware
{
private readonly RequestDelegate _next;
/// <summary>
///
/// </summary>
/// <param name="next"></param>
public RequestMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task InvokeAsync(HttpContext context)
{
context.Request.EnableBuffering();
HttpRequest request = context.Request;
var method = request.Method;
if (method.ToUpper() == "GET")
{
if (!string.IsNullOrEmpty(request.QueryString.Value))
{
var decode = HttpUtility.UrlDecode(request.QueryString.Value);
request.QueryString = new QueryString(decode);
}
}
else
{
try
{
if (!request.ContentLength.HasValue) return;
var syncIOFeature = context.Features.Get<IHttpBodyControlFeature>();
if (syncIOFeature != null)
{
syncIOFeature.AllowSynchronousIO = true;
}
StreamReader stream = new StreamReader(request.Body);
string inputstring = stream.ReadToEnd();
byte[] toEncryptArray = Convert.FromBase64String(inputstring);
//回写流
var requestBodyStream = null;
var requestBodyStream = new MemoryStream();//创建一个流
requestBodyStream.Seek(0, SeekOrigin.Begin);//设置从0开始读取
requestBodyStream.Write(resultArray, 0, resultArray.Length);//把修改写入流中
request.Body = requestBodyStream;//把修改后的内容赋值给请求body
request.ContentLength = requestBodyStream.Length;
request.Body.Seek(0, SeekOrigin.Begin);
request.ContentType = "application/json";
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
await _next(context);//执行下一个内容
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var response = context.Response;
response.ContentType = "application/json";
response.StatusCode = (int)System.Net.HttpStatusCode.OK;
await response.WriteAsync(JsonConvert.SerializeObject(new
{
success = false,
error = new {
code = 500,
}
}));;
}
}
ASP.NET Core 请求体修改回写
最新推荐文章于 2024-09-30 14:28:41 发布