Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have a WebAPI Controller send an http request to another controller within the same service

I have a WebAPI service, and I want it to send an http request to itself. I'd like to confirm what the most appropriate way of doing this looks like. (Normally, I would just instantiate another instance of the target controller or refactor the code behind an interface and then make request that way, but for various reasons I do not want to use that method.)

Is the code below the most appropriate way to make the http request to a different controller within the same service?

using (HttpClient client = new HttpClient())
{
  var httpRequest = new HttpRequestMessage("GET", "https://localhost/SomeOtherController");
  return await client.SendAsync(httpRequest);
}
like image 826
rysama Avatar asked Nov 08 '16 00:11

rysama


People also ask

How do you call a controller action from another controller in Web API?

var ctrl= new MyController(); ctrl. ControllerContext = ControllerContext; //call action return ctrl. Action();


1 Answers

If you need to call another controller, that means there is some shared code there. The best approach is to abstract this piece of code into another class and use it in both controllers.

ex:

public class SomeService
{
 public void DoSomeLogic()
 { 
 }
}

public class FirstController : ApiController
{
 public IHttpActionResult SomeAction()
 {
   new SomeService().DoSomeLogic();
 }
}

public class SecondController : ApiController
{
 public IHttpActionResult SomeOtherAction()
 {
   new SomeService().DoSomeLogic();
 }
}
like image 147
Haitham Shaddad Avatar answered Nov 15 '22 00:11

Haitham Shaddad