如何忽略 ASP.NET Core 中的路由? [英] How to ignore routes in ASP.NET Core?
本文介绍了如何忽略 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 (pre-Core) routes
中是 RouteCollection
而在 .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 中的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文