1. 程式人生 > 其它 >.net 5 利用中介軟體更改介面引數

.net 5 利用中介軟體更改介面引數

    public class InputOutputAlterMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public InputOutputAlterMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<InputOutputAlterMiddleware>();
        }

        
public async Task InvokeAsync(HttpContext context) { var method = context.Request.Method; if (method.Equals("POST")|| method.Equals("GET")) { var dic = new Dictionary<string, StringValues>(); foreach (var item in context.Request.Query.Keys) { dic.Add(item,
new StringValues(context.Request.Query[item].ToString())); } dic.Add("newbarcode", new StringValues("123456")); dic.Remove("barcode"); //修改提交過來的值 context.Request.Form = new FormCollection(dic); using (var ms = new
MemoryStream()) { var orgBodyStream = context.Response.Body; context.Response.Body = ms; context.Response.ContentType = "multipart/form-data"; await _next(context); //using (var sr = new StreamReader(ms)) //{ // ms.Seek(0, SeekOrigin.Begin); // //得到Action的返回值 // var responseJsonResult = sr.ReadToEnd(); // ms.Seek(0, SeekOrigin.Begin); // //如下程式碼若不註釋則會顯示Action的返回值 這裡做了註釋 則清空Action傳過來的值 // // await ms.CopyToAsync(orgBodyStream); // var alterResult = $"沒事返回值【{responseJsonResult}】被我改過來啦!"; // context.Response.Body = orgBodyStream; // //顯示修改後的資料 // await context.Response.WriteAsync(alterResult, Encoding.UTF8); //} } } else { await _next(context); } } } public static class InputOutputAlterMiddlewareExtensions { public static IApplicationBuilder UseInputOutputAlter( this IApplicationBuilder builder) { return builder.UseMiddleware<InputOutputAlterMiddleware>(); } }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseInputOutputAlter();
}