Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web api access controller method from another controller method

I have two different controller --> Controller A,Controller B

And I have different methods each controller and their return values IHttpActionResult (Method A controller A ,Method B and Controller B)

How can I access another controller method and take its content from another controller

Controller B ,and Inside Method B

IHttpActionResult result = ControllerA.MethodA()

and I want to read result.content inside controller B

like image 475
Bilgehan Avatar asked Jun 01 '15 08:06

Bilgehan


1 Answers

When request comes, only controller which should process request is instantiated automatically. You can instantiate second controller manually, but I would recommend to move MethodA functionality either to base controller class

public class BaseController : ApiController
{
   // ...

   public IHttpActionResult MethodA(int id)
   {
       var foo = repository.Get(id);
       if (foo == null)
           return NotFound();

       return Ok(foo);
   }
}

public class ControllerA : BaseController
{
   //...
}

public class ControllerB : BaseController
{
   public IHttpActionResult MethodB(int id)
   {
       var result = MethodA();
       //..
   }
}

or move common logic to separate class (e.g. service), so you would be able to call it from both controllers.

public class ControllerA : ApiController
{
   private IFooService fooService;

   public ControllerA(IFooService fooService)
   {
       this.fooService = fooService;
   }

   public IHttpActionResult MethodA(int id)
   {
      // use fooService.Method()
   }
}

public class ControllerB : ApiController
{
   private IFooService fooService;

   public ControllerB(IFooService fooService)
   {
       this.fooService = fooService;
   }

   public IHttpActionResult MethodB(int id)
   {
        // use fooService.Method()
   }
}
like image 80
Sergey Berezovskiy Avatar answered Sep 21 '22 01:09

Sergey Berezovskiy