How to call a controller method from a class method?

winanjaya 146 Reputation points
2022-12-04T16:27:52.907+00:00

Hi

I have a controller method and how to call it from class method?

controller:

        [HttpPost]  
        [Route("/api/test/Process")]  
        [Authorized]  
        public async Task ProcessAsync([FromServices] Test tp, [FromBody] JObject joData)  
        {  
        }  

class1.cs

private async Task Test()  
{  
     // How to call ProcessAsync internally?  
}  
  
  
  
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-12-04T17:04:31.2+00:00

    You don’t show the controllers constructor, but you need an instance of injected services, an instance of Test and an instance of the jsonData

    var tp = getTest();  
    var jsonObj = getJsonObject();  
    var controller = new MyController(…..); // whatever the constructor needs  
    await controller.processAsync(tp, jsonObj);  
      
    

  2. Anonymous
    2022-12-06T01:46:04.197+00:00

    Many thanks for @Bruce (SqlWork.com) 's code sample and it remind me a lot.

    In my humble opinion, it seems to be not a good idea to call Controller by the services, that's because when we designed a Controller, it should play the role like an entrance & exit so that an http request can reach and got response.

    private readonly HttpClient _httpClient;  
       private readonly IServiceA _servA;  
       private readonly IServiceB _servB;  
      
       public Test(HttpClient httpClient, IServiceA servA, IServiceB servB)  
       {  
                _httpClient = httpClient;  
                _servA = servA;  
                _servB = servB;  
        }  
      
        [HttpPost]  
        [Route("/api/test/Process")]  
        [Authorized]  
        public async Task ProcessAsync([FromServices] Test tp, [FromBody] JObject joData)  
        {  
              //doing service A to get or save some data e.g. var a = _servA.testAsycn(tp);  
              //doing service B to get or save some data e.g. var b = _servB.DoSth(joData);  
              //.....  
              // combine all the data and saving data response into a response and return.  
          
        }  
    

    So your code await tp.TestAsync("myToken...XXXX"); should be abstracted to a service and you need to pass the data Test tp into the service.
    Then your private async Task Test(){} should call the service instead of the controller.

    Calling service method, you may need to use dependency inject.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.