How can I exclude a controller from asp net core 3 attribute routing

Excluding a Controller from ASP.NET Core 3 Attribute Routing

ASP.NET Core 3 introduced attribute routing as a way to define directly on controllers and actions attributes. This provides a more flexible and intuitive way to define routes compared to convention- routing. However, there may be cases where you want to exclude a controller from attribute routing and fall back to convention-based routing. In this article, we will explore how to achieve this in ASP.NET Core 3.

To exclude a controller from attribute routing, you can use the [RouteAttribute] with an empty template on the controller . This will effectively attribute routing for that controller and make it use convention-based routing instead.

[Route("")]
public class HomeController : Controller
{
    // Controller actions and logic
}

By specifying an empty template in the [RouteAttribute], the HomeController will no longer be associated with any specific route. Instead, it will rely on the convention-based routing to determine the appropriate route based on the controller and action names.

It's important to note that if you have multiple controllers with empty route templates, they will all be treated as the default controller and may cause conflicts. In such cases, you can use the [NonControllerAttribute] to exclude a specific class from being considered as a controller.

[NonController]
public class SomeOtherController
{
    // Controller actions and logic
}

The [NonControllerAttribute] ensures that the class is not treated as a controller and will not be in the routing . This can be useful when you have utility classes or helper classes that are mistakenly identified as controllers.

By using techniques, you can easily exclude controllers from attribute routing in ASP.NET Core 3 and fallback to convention-based routing when needed. This provides flexibility in defining routes and allows you to choose the most appropriate routing strategy for your application.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents