如何忽略ASP.NET Core 1.0.1中的路由?

Jef*_*ume 12 asp.net asp.net-mvc asp.net-core-mvc asp.net-core

以前,人们会添加这样的东西Global.aspx.cs,这在.NET Core中已经消失了:

  routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
Run Code Online (Sandbox Code Playgroud)

这是我目前拥有的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" });
  });
Run Code Online (Sandbox Code Playgroud)

问题是,在MVC(预核)routesRouteCollection和.NET的核心是一Microsoft.AspNetCore.Routing.IRouteBuilder所以IgnoreRoute不是一个有效的方法.

Tec*_*ium 16

你可以为此编写中间件.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢,但要把它归结为:我必须用一个完整的自定义路线替换一行代码?看起来有点臃肿. (4认同)

Jes*_*ess 6

.NET 核心 3.1

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

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

  • 啊,很高兴看到这已经变得更好了! (2认同)

小智 5

如果要在没有路由条件的情况下访问静态文件,只需使用内置版本即可StaticFiles Middleware.app.UseStaticFiles(); 在Configure Method中激活它,并将静态文件放在wwwroot目录中.它们适用于HOST/yourStaticFile

有关更多信息,请参阅此处


Zam*_*Zam 5

里面 public void Configure

添加

app.Map("/favicon.ico", delegate { });
Run Code Online (Sandbox Code Playgroud)