services.AddMvc(opt => opt.Filters.Add(new AllowAnonymousFilter()));
The “modern” equivalent for this in ASP.NET Core 3.x and later would be the following:
services.AddControllers(opt => opt.Filters.Add(new AllowAnonymousFilter()));
Alternatively, you can also use AddRazorPages()
or AddControllersWithViews()
depending on how you have your application set up.
But AddMvc
is actually still supported and just literally means the combination of both AddRazorPages()
and AddControllersWithViews()
. Similarly, AddMvcCore
is also still around and is actually called by all those other Add~
methods.
So you can really do any of the following and they mostly do the same thing:
services.AddMvc(opt => opt.Filters.Add(new AllowAnonymousFilter()));
services.AddMvcCore(opt => opt.Filters.Add(new AllowAnonymousFilter()));
services.AddControllers(opt => opt.Filters.Add(new AllowAnonymousFilter()));
services.AddControllersWithViews(opt => opt.Filters.Add(new AllowAnonymousFilter()));
services.AddRazorPages(opt => opt.Filters.Add(new AllowAnonymousFilter()));
Note that this does not really have to do anything with endpoint routing though. The move from AddMvc
to AddControllers
, AddControllersWithViews
and AddRazorPages
was just a way to further split up the underlying framework dependencies so you only pay for those dependencies that you actually need to run your application. E.g. if you only have API controllers, then you don’t need the Razor engine and can opt-out by only calling AddControllers()
.
Endpoint routing on the other hand is what the move from UseMvc
to UseRouting
and UseEndpoints
. This applies to how the middleware pipeline works though, not how the dependencies are set up. For the purpose of registering global MVC filters, you can still configure these globally by configuring the MvcOptions
with one of the Add~
calls from above.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…