本文介绍了如何忽略ASP.NET Core中的路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,人们会在Global.aspx.cs中添加类似的内容,而该内容已在.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(/.*)?" });

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

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" });
  });

问题在于,在MVC(预核心)中,routesRouteCollection,而在.NET Core中,它是Microsoft.AspNetCore.Routing.IRouteBuilder,因此IgnoreRoute不是有效的方法.

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.

推荐答案

您可以编写中间件.

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);
    }
}

这篇关于如何忽略ASP.NET Core中的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:48