canmustu
canmustu

Reputation: 2649

How To Extend the Controller Class With My Custom Methods

I want to get my methods easily from extended controller class and to add some method to the Controller class to use in all other controllers like this:

Extension

public string GetString()
{
    return "iamanexample";
}

AuthenticationController

public class AuthenticationController : Controller
{
   public IActionResult Index()
   {
       string getMyStr = GetString();
       return View();
   }
}

Do I have to create a custom class which inherited by the Controller class and adds my methods in it, and then uses my custom controller class? Or is there any other solution to make it?

Upvotes: 1

Views: 7663

Answers (2)

Riaz Raza
Riaz Raza

Reputation: 382

You can either go for inheritance or you can create extension method of Controller, I prefer the latter version.

To create an extension method, you can create a static class and create a static method in that class.

public static class ControllerExtensions
{
     public static string GetString(this Controller controller)
     {
          return "iamanexample";
     } 
}

Then, you can easily access it through any controller, by writing,

string exampleString = this.GetString();

Upvotes: 5

kaffekopp
kaffekopp

Reputation: 2619

Yes, this is a perfect scenario for inheritance. Create a new controller base class:

public abstract class ControllerBase : Controller 
{
    public string GetString()
    {
        return "iamanexample";
    }
}

Inherit as:

public class AuthenticationController : ControllerBase
{}

Upvotes: 1

Related Questions