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
{}

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

 public class UserController
  {}

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
  {}

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());
            });

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);
        }
    }

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()

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";
        }
    }

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

Please feel free to write comment. Have Fun :)

strathweb.com/2014/06/poco-controllers-asp-..