Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call one web api controller method into another web api project? [closed]

I have two different asp.net core web api projects --> Project A and Project B. I want to call controller method of Project A into controller method of project B.

For example,

Method GetDepartments() is a method of Project A's controller which returns static values. I want to call this method into lets say another method GetStudents() in Project B's controller

like image 485
Jay Bhiyani Avatar asked Dec 30 '19 13:12

Jay Bhiyani


3 Answers

Below Code Sample HttpClient For HttpGet Api:

            [HttpGet]
            public async Task<HttpResponseMessage> GetRequestAsync(HttpRequestMessage Query)
            {                   
                try
                {
                    using (HttpClient client = new HttpClient())
                    {                                                          
                        HttpResponseMessage response = await client.GetAsync("http://localhost:8080/document/quicksearch/"+ Query.RequestUri.Query);

                        if (response.IsSuccessStatusCode)
                        {
                            Console.Write("Success");
                        }
                        else
                        {
                            Console.Write("Failure");
                        }

                        return response;
                    }
                }
                catch (Exception e)
                {        
                    throw e;
                }
            }

Below Code Sample HttpClient For HttpPost Api:

 Public async Task PostRequestAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:6740");

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("", "login")
            });

            var result = await client.PostAsync("/api/Membership/exists", content);

            string resultContent = await result.Content.ReadAsStringAsync();

            Console.WriteLine(resultContent);
        }
    }
like image 128
Amin Golmahalle Avatar answered Sep 27 '22 20:09

Amin Golmahalle


You have to host ProjectA on IIS, then just call the API GetDepartments from that hosted URL, from GetStudents() in Project B's controller.

public class ProjectBController : Controller  
{  
    //your Hosted Base URL
    string Baseurl = "http://192.168.90.1:85/";      
    // GET: Student
    public async Task<ActionResult> GetStudents()  
    {  
        List<Student> StudentInfo = new List<Student>();  

        using (var client = new HttpClient())  
        {  
            //Passing service base url  
            client.BaseAddress = new Uri(Baseurl);  

            client.DefaultRequestHeaders.Clear();  
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  

            //Sending request to find web api REST service resource GetDepartments using HttpClient  
            HttpResponseMessage Res = await client.GetAsync("api/ProjectA/GetDepartments");  

            //Checking the response is successful or not which is sent using HttpClient  
            if (Res.IsSuccessStatusCode)  
            {  

                var ObjResponse = Res.Content.ReadAsStringAsync().Result;  
                StudentInfo = JsonConvert.DeserializeObject<List<Student>>(ObjResponse);  

            }  
            //returning the student list to view  
            return View(StudentInfo);  
        }  
    }  
}  

public class Student
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}
like image 43
Ishwar Gagare Avatar answered Sep 27 '22 20:09

Ishwar Gagare


You shouldn't have to call another project's API controllers from another API controller. You should instead refactor the logic into a common class library and use that from both.

Controllers are meant to be called from the API request/response pipeline.

like image 21
Dave Van den Eynde Avatar answered Sep 27 '22 20:09

Dave Van den Eynde