Burst
Burst

Reputation: 709

ASP.NET Core 2.2 Web API controller inherited from Object class (not from Controller class)

I've seen the following declaration of a controller class in one Web API project:

[Route("api/[controller]")]
public class UrlController
{
    private readonly IConfiguration configuration;

    public UrlController(IConfiguration configuration)
    {
        this.configuration = configuration;
    }

    [HttpGet]
    [ProducesResponseType(typeof(string), 200)]
    public string Get() => this.configuration.GetSection("ShortUrlPrefix").Get<string>();
}

I thought that controllers must inherit from Controller/ControllerBase, but in this case it works without inheritance. Are there any issues with this particular declaration? Is it a kind of "optimization" if we only need to return a simple value (a short string in this case)?

Upvotes: 0

Views: 1332

Answers (1)

Nkosi
Nkosi

Reputation: 247018

Are there any issues with this particular declaration?

No issues.

Controllers usually inherit from Controller, although this isn't required.

The bases controller classes are there if you need more complex scenarios and provides many properties and methods that are useful for handling HTTP requests.

Is it a kind of "optimization" if we only need to return a simple value (a short string in this case)?

That is by design. It is following a convention defined by the framework

Reference Handle requests with controllers in ASP.NET Core MVC

A controller is an instantiable class in which at least one of the following conditions is true:

  • The class name is suffixed with "Controller"
  • The class inherits from a class whose name is suffixed with "Controller"
  • The class is decorated with the [Controller] attribute

Upvotes: 1

Related Questions