6

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);
}
1
  • It seems rather valid, since it's an ordinary HTTP and it does not really matter if it's localhost or not. But I would really advise you not to do that, but reuse the common logic in the shared service as described below. Commented Nov 8, 2016 at 8:36

2 Answers 2

8

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();
 }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'd rather add an ISomeService and depend on it and inject it in the constructor of controller in addition to sharing logic.
Exactly, i just made it short
As roughly mentioned in the OP, I'm aware of ways to refactor code via interfaces or static methods, etc... but that's not the approach I'd like to use here.
2

Yes, this would be an appropriate way to call it.

If you need to do an actual HTTP request then it does not matter that the request goes out to a controller in the same service - it is just a generic HTTP request.

On a side note - you'd probably want to do something about that URI string, so that it is not all hardcoded.

Comments

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.