gpt4 book ai didi

asp.net-core - 如何忽略 ASP.NET Core 中的路由?

转载 作者:行者123 更新时间:2023-12-04 00:12:40 24 4
gpt4 key购买 nike

以前,人们会在 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) routesRouteCollection而在 .NET Core 中,它是一个 Microsoft.AspNetCore.Routing.IRouteBuilder所以 IgnoreRoute不是有效的方法。

最佳答案

你可以写 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);
}
}

关于asp.net-core - 如何忽略 ASP.NET Core 中的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39517816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com