简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM