0

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

0

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

I've never heard this before. Do you know how it's marshalling the controller without some common base class or interface? Is it that it has RouteAttribute applied?
Thanks. I just find it so weird. I mean an interface, I'd understand, but it's got to know somehow that it's a "controller" and should be treated as such. I'm guessing it probably is RouteAttribute. There's no reason to apply that unless you expect the class to function as a controller.
@ChrisPratt naming convention plays a part as well learn.microsoft.com/en-us/aspnet/core/mvc/controllers/… . So it is not necessarily the attribute in this case but the naming convention.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.