-1

Note: Please do not write this off as a duplicate. Kindly read through my complete question.

I have 2 Web API controllers A and B. I need to call a method from controller B in a method in controller A. This, I need it to happen, after some actions have been performed.

class AController : ApiController{
    public IHttpAction SomeMethod(){
        //some action I need to finish before the call for Controller B

        //Call for Controller B
    }
}

class BController : ApiController{
    public IHttpActionResult AnotherMethod(){
        //Some code that I want to be executed after the code in Controller A
    }
}

Please do not suggest me to create another class with a common functionality which is the solution that I commonly found across the web while looking for a solution. I have no common functionality. I just want the execution of code in a linear manner. One after the other. Hopefully, I have been clear. Any help would be appreciated.

2
  • The fact that controller A needs to call controller B and they are in the same project then whatever is being done in controller B is considered common as controller A needs to call it as well. There is a reason you see that common suggestion in you searches. Extract the functionality in controller B into a class that can be injected into controller A and have it call the function. Nothing else to do short of creating a HttpClient and calling the endpoint for controller B. Commented May 15, 2017 at 10:07
  • 1
    Possible duplicate of Web api access controller method from another controller method Commented May 15, 2017 at 10:30

2 Answers 2

6

The idiomatic way is to generally put as little functionality in the controller as possible and just have the controllers acting as endpoints calling into your 'business layer'.

This gives reduces the coupling to Web API and gives you the flexibility to have multiple different endpoints going into your system e.g. you may decide you need a WCF endpoint for whatever reason. Web API may not be around forever, and if you tightly couple your system into Web API you will have a headache on your hands.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed the right answer, except the example of WCF winning over Web API :)
-3

Have you tried this from controller A

new ControllerB().AnotherMethod()

2 Comments

This is not really enough in itself. When Web API initialises controllers it sets things like the Request property which are used by the base class methods used to create responses.
This is not a good practise. You making your controller class dependant on ControllerB by newing it up.

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.