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
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()
   }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With