简体   繁体   English

直接从另一个Web API控制器内部调用另一个Web API控制器

[英]Calling another Web API controller directly from inside another Web API controller

Given a controller Proxy and an action of GetInformation . 给定控制器ProxyGetInformation的动作。 I want to be able to call the method GetInformation of the Users controller. 我希望能够调用Users控制器的方法GetInformation Both the WebAPI controllers are in the same project but direct calls like 两个WebAPI控制器都在同一个项目中,但直接调用如

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. 我不想做完整的重定向响应,因为我不希望外部公开UserController路由。 This needs to be an internal only call. 这需要是内部唯一的呼叫。

For those wanting to solve this API to API method in different controllers, we have found a solution that works. 对于那些想要在不同控制器中将API解析为API方法的人,我们找到了一个有效的解决方案。 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. 这里最大的复杂性是Uri调整。

You should do something like this in your UsersController 您应该在UsersController中执行类似的操作

public HttpResponseMessage GetInformation(InformationRequest request)
{
    HttpResponseMessage resp ;

    resp = UserBusinessLogic.GetInformation(request) ;

    return resp ;
}

and from your ProxyController you can resuse that "UserBusinessLogic" method to obtain the same information using the same code snippet. 从您的ProxyController,您可以重新使用“UserBusinessLogic”方法,以使用相同的代码片段获取相同的信息。

Another way can be: 另一种方式可以是:

IQueryable<Users> GetInformation()

without using the IHttpActionResult return type. 不使用IHttpActionResult返回类型。 Your method will still remain an Http GET method and then call it in the same way as you call any class method. 您的方法仍将是一个Http GET方法,然后以与调用任何类方法相同的方式调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM