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

后端 未结 3 1022
死守一世寂寞
死守一世寂寞 2021-02-04 13:38

Given a controller Proxy and an action of GetInformation. I want to be able to call the method GetInformation of the Users c

相关标签:
3条回答
  • 2021-02-04 14:30

    You should do something like this in your 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.

    0 讨论(0)
  • 2021-02-04 14:40

    Another way can be:

    IQueryable<Users> GetInformation()
    

    without using the IHttpActionResult return type. Your method will still remain an Http GET method and then call it in the same way as you call any class method.

    0 讨论(0)
  • 2021-02-04 14:41

    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.

    0 讨论(0)
提交回复
热议问题