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);
}
var ctrl= new MyController(); ctrl. ControllerContext = ControllerContext; //call action return ctrl. Action();
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();
}
}
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