DEV Community

Huseyin Simsek
Huseyin Simsek

Posted on • Updated on

Define Controllers In Asp.Net Core

There are 4 types of way define controllers in Asp.Net Core:

1- Inherit from ControllerBase class

public class UserController : ControllerBase
{}
Enter fullscreen mode Exit fullscreen mode

2- Define a controller with a Name that Contains "Controller" suffix.

 public class UserController 
  {}
Enter fullscreen mode Exit fullscreen mode

You can define Controller without inherit ControllerBase class. However you have to define specific name class that includes 'Controller' suffix.

3- Define With Controller Attribute

    [Controller]
    public class User
    {}
Enter fullscreen mode Exit fullscreen mode

4- Define Custom Controller Type Class
You can define custom controller like the second step.
For using this way, you have to add service configuration in StartUp.cs.

services.AddMvc()
            .ConfigureApplicationPartManager(pm=> 
            {
                pm.FeatureProviders.Add(new ControllerEndpointFeatureProvider());                
            });
Enter fullscreen mode Exit fullscreen mode

Then you create ControllerEndpointFeatureProvider class:

 public class ControllerEndpointFeatureProvider : ControllerFeatureProvider
    {
// Override IsController method and configure custom 
        protected override bool IsController(TypeInfo typeInfo)
        {
            var isController = base.IsController(typeInfo);
            return isController || 
typeInfo.Name.EndsWith("EndPoint", StringComparison.OrdinalIgnoreCase);
        }
    } 
Enter fullscreen mode Exit fullscreen mode

ControllerFeatureProvider has two important methods. One of these is IsController. You can override that method to create specific controller type. For example, We introduce controllers type with the end of "EndPoint".
Each class is checked whether it's a controller or not when building project. Thus, you can define the controller class with a name that contains "EndPoint" suffix.

public UserEndPoint()
{}
Enter fullscreen mode Exit fullscreen mode

Bonus:
You can suspend controller features with NonController attribute from a controller class . So you cannot reach to this controller with Http Requests

    [NonController]
    [Route("api/[controller]")]
    public class User: ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "beta";
        }
    }
Enter fullscreen mode Exit fullscreen mode

For example, you cannot get information from this controller until you don't remove NonController attribute.

Please feel free to write comment. Have Fun :)

https://www.strathweb.com/2014/06/poco-controllers-asp-net-vnext/

Top comments (0)