【问题标题】:How to ignore routes in ASP.NET Core?如何忽略 ASP.NET Core 中的路由?
【发布时间】:2016-09-15 18:17:40
【问题描述】:

以前,人们会在 Global.aspx.cs 中添加类似这样的内容,而 .NET Core 中没有:

  routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

这是我目前在我的 Startup.cs 中拥有的内容(适用于 .NET Core):

  app.UseDefaultFiles();

  app.UseStaticFiles();

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

      routes.MapSpaFallbackRoute(
          name: "spa-fallback",
          defaults: new { controller = "Home", action = "Index" });
  });

问题在于,在 MVC(pre-Core)中,routes 是 RouteCollection,而在 .NET Core 中则是 Microsoft.AspNetCore.Routing.IRouteBuilder,因此 IgnoreRoute 不是有效方法。

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

    您可以为此写middleware。

    public void Configure(IApplciationBuilder app) {
        app.UseDefaultFiles();
    
        // Make sure your middleware is before whatever handles 
        // the resource currently, be it MVC, static resources, etc.
        app.UseMiddleware<IgnoreRouteMiddleware>();
    
        app.UseStaticFiles();
        app.UseMvc();
    }
    
    public class IgnoreRouteMiddleware {
    
        private readonly RequestDelegate next;
    
        // You can inject a dependency here that gives you access
        // to your ignored route configuration.
        public IgnoreRouteMiddleware(RequestDelegate next) {
            this.next = next;
        }
    
        public async Task Invoke(HttpContext context) {
            if (context.Request.Path.HasValue &&
                context.Request.Path.Value.Contains("favicon.ico")) {
    
                context.Response.StatusCode = 404;
    
                Console.WriteLine("Ignored!");
    
                return;
            }
    
            await next.Invoke(context);
        }
    }
    

    【讨论】:

    • 非常感谢,但归结为:我必须用整个自定义路由替换一行代码?看起来有点臃肿。
    • 也许吧? .NET Core 中可能有一种方法可以更直接地解决您的问题。也许通过路由中间件。我只是没有遇到它。我会阅读这份文档,然后查看源代码以获得更明确的信息:docs.asp.net/en/latest/fundamentals/routing.html
    • 这个解决方案是有意义的,但应该更具体,寻找包含提供的字符串的路径意味着您不想匹配的潜在路径将被匹配,这也不是非常理想的,它就性能而言,不使用中间件并将路由数量保持在最低限度会更好。
    • 为了解决 Bonner 的问题,Contains(...) 应该替换为 StartsWith("/favicon.ico")。否则,一个很好的答案。
    • 这可行,但请参阅下面的答案以获得更简单的解决方案。
    【解决方案2】:

    .NET Core 3.1

    对于带有端点路由的 .NET Core 3.1,这似乎是最简单的方法。您不需要为这个简单的案例构建中间件。

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/favicon.ico", async (context) =>
        {
            context.Response.StatusCode = 404;
        });
        // more routing
    });
    

    【讨论】:

    • 啊,很高兴看到这变得更好了!
    【解决方案3】:

    如果您想在没有路由条件的情况下访问静态文件,只需使用内置StaticFiles Middleware。 使用app.UseStaticFiles(); 激活它 在配置方法中并将您的静态文件放在 wwwroot 目录中。 它们在 HOST/yourStaticFile 上可用

    更多信息,请参考here

    【讨论】:

      【解决方案4】:

      在public void Configure内

      添加

      app.Map("/favicon.ico", delegate { });
      

      【讨论】:

      • 如果您正在使用 swagger 并且还想忽略控制器(仍然需要此答案),还添加 [ApiExplorerSettings(IgnoreApi = true)] 将从 swagger 文档中删除
      • 此答案有效,但在 .NET Core 3.1 中会引发异常 System.InvalidOperationException: The request reached the end of the pipeline without executing the endpoint: '/favicon.ico HTTP: GET'. Please register the EndpointMiddleware using 'IApplicationBuilder.UseEndpoints(...)' if using routing.。
      • @Jess 很高兴知道。最初的答案是针对 .NET Core 1.0.1
      【解决方案5】:

      允许路由处理程序解析网站图标请求,并将您的路由保持在最低限度。避免使用中间件,这只会增加代码的复杂性,意味着所有其他请求必须在路由处理程序之前通过中间件,这对于繁忙的网站来说性能更差。对于不忙的网站,您只是在浪费时间担心这一点。

      见https://github.com/aspnet/Routing/issues/207

      【讨论】:

        【解决方案6】:

        在 ASP.NET Core 中,您可以编写一个受约束的包罗万象的路由模板。为此,在您的 ASP.NET Core 示例中,将对 routes.MapSpaFallbackRoute 的调用替换为以下内容:

        // Returns the home/index page for unknown files, except for
        // favicon.ico, in which case a 404 error is returned.
        routes.MapRoute(
            name: "spa-fallback",
            template: "{*url:regex(^(?!favicon.ico).*$)}",
            defaults: new { Controller = "Home", action = "Index" });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-25
          • 2010-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-30
          • 1970-01-01
          • 2015-03-17
          相关资源
          最近更新 更多