温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在asp.net core的中间件中返回具体的页面

发布时间:2021-12-06 11:53:32 来源:亿速云 阅读:99 作者:iii 栏目:云计算

这篇文章主要讲解了“怎么在asp.net core的中间件中返回具体的页面”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么在asp.net core的中间件中返回具体的页面”吧!

前言

在 asp.net core 中,存在着中间件这一概念,在中间件中,我们可以比过滤器更早的介入到 http 请求管道,从而实现对每一次的 http 请求、响应做切面处理,从而实现一些特殊的功能

在使用中间件时,我们经常实现的是鉴权、请求日志记录、全局异常处理等等这种非业务性的需求,而如果你有在 asp.net core 中使用过 swashbuckle(swagger)、health check、mini profiler 等等这样的组件的话,你会发现,这些第三方的组件往往都提供了页面,允许我们通过可视化的方式完成某些操作或浏览某些数据

Step by Step

最终实现的功能其实很简单,当用户跳转到某个指定的地址后,自定义的中间件通过匹配到该路径,从而返回指定的页面,所以这里主要会涉及到中间件是如何创建,以及如何处理页面中的静态文件引用

因为这块并不会包含很多的代码,所以这里主要是通过分析 Swashbuckle.AspNetCore 的代码,了解它是如何实现的这一功能,从而给我们的功能实现提供一个思路

在 asp.net core 中使用 Swashbuckle.AspNetCore 时,我们通常需要在 Startup 类中针对组件做如下的配置,根据当前程序的信息生成 json 文件 =》 公开生成的 json 文件地址 =》 根据 json 文件生成可视化的交互页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class Startup
{
   // This method gets called by the runtime. Use this method to add services to the container.
   public void ConfigureServices(IServiceCollection services)
   {
       // 生成 swagger 配置的 json 文件
       services.AddSwaggerGen(s =>
       {
           s.SwaggerDoc("v1", new OpenApiInfo
           {
               Contact = new OpenApiContact
               {
                   Name = "Danvic Wang",
                   Url = new Uri("https://yuiter.com"),
               },
               Description = "Template.API - ASP.NET Core 后端接口模板",
               Title = "Template.API",
               Version = "v1"
           });

           // 参数使用驼峰的命名方式
           s.DescribeAllParametersInCamelCase();
       });
   }

   // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
   {
       // 公开 swagger 生成的 json 文件节点
       app.UseSwagger();

       // 启用 swagger 可视化交互页面
       app.UseSwaggerUI(s =>
       {
           s.SwaggerEndpoint($"/swagger/v1/swagger.json",
               $"Swagger doc v1");
       });
   }
}

可以看到最终呈现给用户的页面,其实是在 Configure 方法中通过调用 UseSwaggerUI 方法来完成的,这个方法是在 Swashbuckle.AspNetCore.SwaggerUI 这个程序集中,所以这里直接从 github 上找到对应的文件夹,clone 下源代码,来看下是如何实现在中间件中返回特定的页面

在 clone 下的代码中,排除掉一些 c#、node.js 使用到的项目性文件,可以看到整个项目中的文件按照功能可以分为三大块,其中最核心的则是在 SwaggerUIMiddleware 类中,因此,这里主要聚焦在这个中间件类的实现

怎么在asp.net core的中间件中返回具体的页面

在一个 asp.net core 中间件中,核心的处理逻辑是在 Invoke/InvokeAsync 方法中,结合我们使用 swagger 时的场景,可以看到,在将组件中所包含的页面呈现给用户时,主要存在如下两个处理逻辑

1、当匹配到用户访问的是 /swagger 时,返回 301 的 http 状态码,浏览器重定向到 /swagger/index.html,从而再次触发该中间件的执行

2、当匹配到请求的地址为 /swagger/index.html 时,将嵌入到程序集中的文件通过 stream 流的形式获取到,转换成字符串,再指定请求的响应的类型为 text/html,从而实现将页面返回给用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public async Task Invoke(HttpContext httpContext)
{
   var httpMethod = httpContext.Request.Method;
   var path = httpContext.Request.Path.Value;

   // If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
   if (httpMethod == "GET" && Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$"))
   {
       // Use relative redirect to support proxy environments
       var relativeRedirectPath = path.EndsWith("/")
           ? "index.html"
           : $"{path.Split('/').Last()}/index.html";

       RespondWithRedirect(httpContext.Response, relativeRedirectPath);
       return;
   }

   if (httpMethod == "GET" && Regex.IsMatch(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?index.html$"))
   {
       await RespondWithIndexHtml(httpContext.Response);
       return;
   }

   await _staticFileMiddleware.Invoke(httpContext);
}

这里需要注意,因为类似于这种功能,我们可能会打包成独立的 nuget 包,然后通过 nuget 进行引用,所以为了能够正确获取到页面及其使用到的静态资源文件,我们需要将这些静态文件的属性修改成嵌入的资源,从而在打包时可以包含在程序集中

对于网页来说,在引用这些静态资源文件时存在一种相对的路径关系,因此,这里在中间件的构造函数中,我们需要将页面需要使用到的静态文件,通过构建 StaticFileMiddleware 中间件,将文件映射与网页相同的 /swagger 路径下面,从而确保页面所需的资源可以正确加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class SwaggerUIMiddleware
{
   private const string EmbeddedFileNamespace = "Swashbuckle.AspNetCore.SwaggerUI.node_modules.swagger_ui_dist";

   private readonly SwaggerUIOptions _options;
   private readonly StaticFileMiddleware _staticFileMiddleware;

   public SwaggerUIMiddleware(
       RequestDelegate next,
       IHostingEnvironment hostingEnv,
       ILoggerFactory loggerFactory,
       SwaggerUIOptions options)
   {
       _options = options ?? new SwaggerUIOptions();

       _staticFileMiddleware = CreateStaticFileMiddleware(next, hostingEnv, loggerFactory, options);
   }

   private StaticFileMiddleware CreateStaticFileMiddleware(
       RequestDelegate next,
       IHostingEnvironment hostingEnv,
       ILoggerFactory loggerFactory,
       SwaggerUIOptions options)
   {
       var staticFileOptions = new StaticFileOptions
       {
           RequestPath = string.IsNullOrEmpty(options.RoutePrefix) ? string.Empty : $"/{options.RoutePrefix}",
           FileProvider = new EmbeddedFileProvider(typeof(SwaggerUIMiddleware).GetTypeInfo().Assembly, EmbeddedFileNamespace),
       };

       return new StaticFileMiddleware(next, hostingEnv, Options.Create(staticFileOptions), loggerFactory);
   }
}

怎么在asp.net core的中间件中返回具体的页面

当完成了页面的呈现后,因为一般我们会创建一个单独的类库来实现这些功能,在页面中,可能会包含前后端的数据交互,由于我们在宿主的 API 项目中已经完成了对于路由规则的设定,所以这里只需要在类库中通过 nuget 引用 Microsoft.AspNetCore.Mvc.Core ,然后与 Web API 一样的定义 controller,确保这个中间件在宿主程序的调用位于路由匹配规则之后即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   if (env.IsDevelopment())
   {
       app.UseDeveloperExceptionPage();
   }

   app.UseHttpsRedirection();

   app.UseRouting();

   app.UseAuthorization();

// Endpoint 路由规则设定
   app.UseEndpoints(endpoints =>
   {
       endpoints.MapControllers();
   });

   // 自定义中间件
   app.UseMiddleware<SampleUIMiddleware>();
}

感谢各位的阅读,以上就是“怎么在asp.net core的中间件中返回具体的页面”的内容了,经过本文的学习后,相信大家对怎么在asp.net core的中间件中返回具体的页面这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI