0

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?

2
  • 1
    You're in the same application. There's no need to make one controller call another through a HTTP request. If you have some logic that both controllers need, abstract it out to a separate class that both controllers can call. Commented Jul 28, 2022 at 19:10
  • You need to move logic functionality into a Service class, your controllers has to be dummy and just call to the method into a service class. Commented Jul 30, 2022 at 3:50

1 Answer 1

1

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

Comments

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.