Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore routes in ASP.NET Core?

Previously, one would add something like this to Global.aspx.cs, which is gone in .NET Core:

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

Here's what I currently have in my Startup.cs (for .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" });
  });

The problem is that in MVC (pre-Core) routes was a RouteCollection and in .NET Core it's a Microsoft.AspNetCore.Routing.IRouteBuilder so IgnoreRoute is not a valid method.

like image 292
Jeff Guillaume Avatar asked Sep 15 '16 18:09

Jeff Guillaume


People also ask

How do I ignore a route in .NET Core?

NET Core: routes. IgnoreRoute("{*favicon}", new { favicon = @"(. */)?

What does the IgnoreRoute () method do?

Ignores the specified URL route for the given list of available routes.

What is UseEndpoints in ASP.NET Core?

UseEndpoints adds endpoint execution to the middleware pipeline. It runs the delegate associated with the selected endpoint.


1 Answers

You could write middleware for this.

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);
    }
}
like image 183
Technetium Avatar answered Sep 17 '22 16:09

Technetium