直接从另一个Web API控制器内部调用另一个Web API控制器 [英] Calling another Web API controller directly from inside another Web API controller
问题描述
给出一个控制器 Proxy
和一个 GetInformation
动作.我希望能够调用 Users
控制器的方法 GetInformation
.两个WebAPI控制器都在同一个项目中,但是直接调用如
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);
不起作用.
签名是:
public HttpResponseMessage GetInformation(InformationRequest request)
我不想执行完整的重定向响应,因为我不想将UserController路由暴露给外部.这必须是仅供内部使用的呼叫.
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.
推荐答案
对于那些希望在不同控制器中解决此API到API方法的人,我们找到了一个可行的解决方案.最初的尝试很接近,只是缺少了一些东西.
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);
这样做可以构建目标控制器并直接调用所需的方法.这里最大的复杂性是Uri调整.
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.
这篇关于直接从另一个Web API控制器内部调用另一个Web API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!