Home > Software engineering >  ASP.NET use local API Controller Endpoint
ASP.NET use local API Controller Endpoint

Time:07-31

I currently have two separate API Controllers in a single project. Controller B requires some functionalities covered by controller A. What I would like to achieve is to acces an endpoint from A from within B. However, I could not figure out how to get a reference to an instance of any controller, thus I cannot reference them at all. So my only options seem to be to make every method static or to call the endpoints using localhost:{port} as URI - but both would seem like bad practice (especially the last one).

So, how do I call the methods from controller A from within controller B?

CodePudding user response:

First Create a Common class and put your common logic inside some method like below:

public class Common
{
  public string CommonMethod()
  { 
    return "something";
  }
}

Now your both controller will look like the below:

1. Let's suppose Controller B will be:

public class BController : Controller
{
  Common _common=new Common();
  string result=_common.CommonMethod();
}

2. Let's suppose Controller A will be:

public class AController : Controller
{
  Common _common=new Common();
  string result=_common.CommonMethod();
}
  • Related