Matias Cicero
Matias Cicero

Reputation: 26321

Making a controller not visible to the client in ASP.NET WEB API (or MVC)

Let's suppose I have a layer of abstract controllers, which delegates the request to its child controller class, until it reaches the implementation.

Think of it like a pipeline of controllers, that the request must go through, and includes caching the responses, authorizing and authenticating the user, validating the input and output data, handling repository access, etc.

My leaf class (the last child of the hierarchy), may have the following signature:

public class SeasonsController : DefaultPersistenceRestController
                                 <int, Season, SeasonPutDTO, SeasonPostDTO, SeasonQueryData> {
      /** Controller implementation here  **/
}

The base classes have a lot of reusable code located in one module, this is good and has helped me a lot when changing the logic of my controllers at a global level.

Now, suppose SeasonsController need to call EpisodesController, for irrelevant reasons.

The call would be like this:

EpisodesController episodeController = new EpisodesController();
//Do something with EpisodesController

The problem is that I don't want EpisodesController to be accessed from the outside, such as client's request. ASP.NET automatically identifies controllers and creates a public endpoint for them, such as http://localhost:80/episodes.

I created EpisodesController because it uses a lot of logic from the controller's base classes, but I intend to use it internally.

I can desactivate authentication, authorization, cache and all other stuff that will be useless if a controller is used in this way, so that's not a problem.

However, I cannot manage to prevent ASP.NET to ignore my EpisodesController class, and to not consider it like a controller.

Is there an attribute or annotation maybe that will tell the compiler to do this? Maybe some modification in Web.config?.

Also note that I don't want to change EpisodesController's class name to another name, as it is really a controller, but an internal one.

Upvotes: 2

Views: 2513

Answers (2)

Patko
Patko

Reputation: 4423

You could try to use the IgnoreRoute extension method. Or you could try the internal as suggested by beautifulcoder. If it's in another assembly (and you can modify it) you could also make it visible to other assemblies with InternalsVisibleToAttribute.

Although to be honest, using one controller within another controller doesn't seem right to me. I would try and refactor you common functionality to services/helpers, then you could probably also make your EpisodesController into a simple service. Composition over inheritance and all that :)

Upvotes: 3

beautifulcoder
beautifulcoder

Reputation: 11340

If you make a controller public it will be accessible. From what I understand, you can change it to protected or internal.

Upvotes: 1

Related Questions