如何在.NET Core的每个页面上添加Intranet样式标头(从Web处理程序返回的字符串)

时间:2019-05-23 11:49:14

标签: c# asp.net-core asp.net-core-middleware

在.NET Core Web应用程序中,我正在使用中间件(app.UseMyMiddleware)向响应添加Intranet标头。限制是格式化响应的处理程序(MyResponseHandler.FormatResponse)不能更改,因为它已在旧版应用程序上使用并返回字符串值。我已经使其正常工作了,但希望将处理限制为仅页面请求,而不是处理通过的每个请求(即css / js / images等)。

FormatResponse基本上只是将当前响应作为字符串接收,找到“ body”标签,并附加HTML负载,从而创建一个漂亮的菜单栏以访问所有其他应用程序。

首先,这是在.NET Core中实现通用标头的好方法吗? 到目前为止,我发现的所有内容都只是说要使用“布局”页面,该页面仅适用于单个应用程序,但不适用于使用不同框架编写的大量应用程序。

第二,如何过滤仅页面请求? 我可以过滤所有不包含“。”的页面但是如果有一个'。以查询字符串为例?我也不确定MVC或剃须刀页面是否带有“。”。在网址中(不是我到目前为止所看到的)。

第三,有没有更有效的方法?遍历每个请求的所有这些代码似乎会使速度变慢。我可以更早进行过滤以保存代码执行,还是有其他方法?

Startup.cs

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(MiddlewareExtensions.GenericExceptionHandler);
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseMyMiddleware();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

MiddlewareExtensions.cs

        public static void UseMyMiddleware(this IApplicationBuilder app)
        {
            app.UseMiddleware<LoadIntranetHeader>();
        }

LoadIntranetHeader.cs

    public class LoadIntranetHeader
    {
        private readonly RequestDelegate _next;

        public LoadIntranetHeader(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var originalBodyStream = context.Response.Body;
            var config = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration));

            using (var responseBody = new MemoryStream())
            {
                context.Response.Body = responseBody;

                await _next(context);

                context.Response.Body = originalBodyStream;

                responseBody.Seek(0, SeekOrigin.Begin);
                string response = new StreamReader(responseBody).ReadToEnd();

                if (!context.Request.Path.ToString().Contains(".") 
                    && !context.Request.Path.ToString().Contains("/api/", StringComparison.CurrentCultureIgnoreCase))
                {
                       response = MyResponseHandler.FormatResponse(config, response);
                }
                await context.Response.WriteAsync(response);
            }
        }
    }

0 个答案:

没有答案