ASP.NET Core中API与MVC端点的过滤器分离方案问询
Absolutely! You can cleanly separate filters for MVC controllers and Web API controllers in ASP.NET Core—here are a few straightforward approaches to achieve this:
1. Register Filters Targeted to MVC/API During Service Configuration
Starting with ASP.NET Core 3.0+, the framework splits MVC (with views) and Web API registration into distinct extension methods, which makes scope-based filter registration trivial:
Add Web API-only filters
UseAddControllers()to configure settings specifically for API controllers (which inherit fromControllerBase):services.AddControllers(options => { // This filter will only apply to Web API controllers options.Filters.Add<ApiExclusiveFilter>(); });Add MVC-only filters
UseAddControllersWithViews()to configure settings for MVC controllers (which inherit fromControllerand handle view rendering):services.AddControllersWithViews(options => { // This filter will only apply to MVC controllers with views options.Filters.Add<MvcExclusiveFilter>(); });
This method is the cleanest because it leverages the framework's built-in separation of MVC and API pipelines.
2. Add Conditional Logic Inside Filters
If you need a single filter to behave differently for MVC vs API requests, you can check the controller type in the filter's logic:
public class CrossCuttingFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { // Check if the controller is an API controller (inherits ControllerBase) if (context.Controller is ControllerBase) { // Execute logic exclusive to Web API requests Console.WriteLine("Running API-specific filter logic"); } // Check if the controller is an MVC controller (inherits Controller) else if (context.Controller is Controller) { // Execute logic exclusive to MVC requests Console.WriteLine("Running MVC-specific filter logic"); } } public void OnActionExecuted(ActionExecutedContext context) { // Apply post-action conditional logic here } }
This works well when you want shared core logic with branch-specific behavior for MVC/API.
3. Use Attribute-Based Filter Targeting
You can also apply filters directly to controller classes using attributes, ensuring they only run on the intended type:
For API controllers:
[TypeFilter(typeof(ApiOnlyFilter))] [ApiController] [Route("api/[controller]")] public class UsersController : ControllerBase { // API actions here }For MVC controllers:
[TypeFilter(typeof(MvcOnlyFilter))] public class HomeController : Controller { // MVC actions with views here }
This approach is great for granular control over individual controllers or actions.
All these methods let you fully isolate MVC and Web API filters, so they won't interfere with each other. Pick the one that best fits your project's structure and requirements!
内容的提问来源于stack exchange,提问作者Robert

