Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling another Web API controller directly from inside another Web API controller

Given a controller Proxy and an action of GetInformation. I want to be able to call the method GetInformation of the Users controller. Both the WebAPI controllers are in the same project but direct calls like

var controller = new UsersController();
return controller.GetInformation(request);

Doesn't work.

The signature is:

public HttpResponseMessage GetInformation(InformationRequest request)

I do not want to do a full redirect response as I do not want the UserController route exposed externally. This needs to be an internal only call.

like image 729
VulgarBinary Avatar asked Jan 28 '26 11:01

VulgarBinary


1 Answers

For those wanting to solve this API to API method in different controllers, we have found a solution that works. The initial attempt was close, just missing a few things.

var controller = new UserAccountController
{
   Request = new HttpRequestMessage(HttpMethod.Post, Request.RequestUri.AbsoluteUri.Replace("/current/route", "/route/to_call"))
};
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration();
return controller.GetInformation(request);

In doing this it allows construction of the target controller and direct invocation of the method desired. The biggest complexity here is the Uri adjustment.

like image 68
VulgarBinary Avatar answered Jan 31 '26 04:01

VulgarBinary