ASP.NET Core多种类型的Web融合案例

问题描述 投票:0回答:1

我创建了一个 ASP.NET Core MVC 项目,但我想添加对 Web API 和 SignalR 的支持。我知道Web API请求和MVC请求都经过统一的请求管道。我想问的是,如果我按照MVC模式配置请求管道,并添加很多中间件,当Web API请求经过很多中间件处理时,会不会消耗很多不必要的性能?

如果确实很浪费性能,那么有没有合理的请求管道配置方案呢?让Web API请求只通过需要的中间件,我知道你可以使用

app.UseWhen()
方法,但是我想学习如何配置以下成熟的项目,真棒你可以分享经验或类似的项目模板。

谢谢大家!

public static void UseMyEndpoints(this IApplicationBuilder application)
{
     application.UseEndpoints(endpoints =>
     {
         // SignalR                
         endpoints.MapHub<...>(...);
         
        // MVC  
         EngineContext.Current.Resolve<IRoutePublisher>().RegisterRoutes(endpoints);
         
         // WebApi
         endpoints.MapControllers();
     });
}

app.UseMyProxy();
app.UseLinqQueryCache();
app.UseMyResponseCompression();
app.UseMyWebOptimizer();
app.UseMyStaticFiles();
app.UseMyWEbMarkupMin();
app.UseKeepAlive();
app.UseSession();
app.UseMyRequestLocalization();
app.UseMyRouting();
app.UseMyCors();
app.UseMyAuthentication();
app.UseAuthorization()
app.UseMyEndpoints();
c# asp.net-core asp.net-core-mvc asp.net-core-webapi asp.net-core-signalr
1个回答
0
投票

关于你的问题,是的。 配置 ASP.NET Core 应用程序的请求管道时,必须考虑性能影响,尤其是在处理多个中间件组件时。添加不必要的中间件确实会影响性能,因为每个中间件组件在处理请求时都会引入一些开销。 关于您想要的代码,您可以使用这个适合我的模板:

public static void UseMyEndpoints(this IApplicationBuilder application)
{
  application.UseRouting(); // Enable endpoint routing

  application.UseEndpoints(endpoints =>
  {
     // SignalR
     endpoints.MapHub<...>(...);

     // MVC
     endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    // Web API
    endpoints.MapControllers();
});
}
  • UseRouting() 启用端点路由,这对于 MVC 和 Web API 路由都是必需的。

  • 对于MVC,您可以使用MapControllerRoute来定义常规的MVC路由。

  • 对于 Web API,MapControllers() 映射属性路由控制器。

© www.soinside.com 2019 - 2024. All rights reserved.