Share via


Pass Paramater from MVC Controller to Web API Controller

Question

Friday, March 1, 2019 10:28 PM

Hello,

I called WebAPI from ajax and I passed parameter and its work.. but I want to pass parameter from MVC Controller ( Server Side ) to WebAPI Controller ??

API Controller ....

public class GroupAPIController : ApiController

    {
        public void PostGroup(int number) // Number Parameter
        {
            // Run code
        }

        public void PostGroup(Group obj) // Object Parameter
        {
            // Run Code
        }

        public Group GetGroup(int id) // Return Object by send ID
        {
            // run Code
        }
}

MVC Controller >> I tried below code but its not working, I don't know how this code working?

 public async Task<ActionResult> Save()
        { 
            vmGroup objvmGroup = new vmGroup();
            Group objGroup = new Group();
            objGroup.Name = "Test";
            objGroup.Status = 1;

            List<Group> ListGroup = new List<Group>();
            string apiUrl = ConfigurationManager.AppSettings["baseurl"] + "/Application.API/api/GroupAPI";
            var Param = new
            {
                id = 1
            };
            string inputJson = (new JavaScriptSerializer()).Serialize(Param);
            WebClient client = new WebClient();
            client.Headers["content-type"] = "application/json";
            client.Encoding = Encoding.UTF8;
            string json = client.UploadString(apiUrl, inputJson);
            
            objvmGroup.ListGroup = ListGroup ;
            return View("NewGroup", objvmGroup);
        }

Please, If someone can help me. Thankful for all

All replies (6)

Sunday, March 3, 2019 9:50 AM âś…Answered

Thanks for All,

I tried this code and its working fine:

 vmGroup objvmGroup = new vmGroup();
            string apiUrl = ConfigurationManager.AppSettings["baseurl"] + "/Application.API/SaveObject";
            var client = new HttpClient();
            client.BaseAddress = new Uri(apiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            Group obj = new Group();
            obj.ID = 5;
            obj.Name = "AA";
            HttpResponseMessage responseMessage = await client.PostAsJsonAsync(apiUrl,obj);
            if (responseMessage.IsSuccessStatusCode)
            {
                var responseData = responseMessage.Content.ReadAsStringAsync().Result;   
            }

            return View(objvmGroup);

Friday, March 1, 2019 10:59 PM

Khalid Salameh

I called WebAPI from ajax and I passed parameter and its work.. but I want to pass parameter from MVC Controller ( Server Side ) to WebAPI Controller ??

If you want to invoke a Web API action over HTTP using code, then use HttpClient.

/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Other than that, have you tried running the code through the debugger to see what's happening?  Perhaps there is an error?


Saturday, March 2, 2019 12:48 AM

It happens to be in VB.NET but it shows how to make the calls to WebAPI from ASP.NET MVC code that is being called by the controller through an object in the Models folder.

Imports System.Net
Imports Entities
Imports Newtonsoft.Json

Namespace WebApi
    Public Class WebApi
        Implements IWebApi

        #Region "Project"
        public Function  GetProjsByUserIdApi(userid As String) as List(of DtoProject) Implements IWebApi.GetProjsByUserIdApi

            dim dtoprojects = new List(Of DtoProject)

            dim url = "http://localhost/WebApiVB/api/project/GetProjectsByUserId?userid=" & userid

            Using webclient As New WebClient
                dim json  = webclient.DownloadString(url)
                Dim projects = JsonConvert.DeserializeObject(of List(Of DtoProject))(json)
                dtoprojects = projects
            End Using

            Return dtoprojects

        End Function
       
        public Function GetProjByIdApi(id As int32) as DtoProject Implements IWebApi.GetProjByIdApi

            dim dto as DtoProject

            dim url = "http://localhost/WebApiVB/api/project/GetProjectById?id=" & id

            Using webclient As New WebClient
                dim json  = webclient.DownloadString(url)
                Dim project = JsonConvert.DeserializeObject(of DtoProject)(json)
                dto = project
            End Using
           
            Return dto

        End Function

        public sub CreateProjectApi(dto As DtoProject) Implements IWebApi.CreateProjectApi

            Dim reqString As byte()

            Using webclient As New WebClient

                dim url as string = "http://localhost/WebApiVB/api/project/CreateProject"
                webClient.Headers("content-type") = "application/json"
                reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                webClient.UploadData(url, "post", reqString)

            End Using
            
        End sub
        
        public sub UpdateProjectApi(dto As DtoProject) Implements IWebApi.UpdateProjectApi

            Dim reqString As byte()

            Using webclient As New WebClient

                dim url as string = "http://localhost/WebApiVB/api/project/UpdateProject"
                webClient.Headers("content-type") = "application/json"
                reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                webClient.UploadData(url, "post", reqString)

            End Using

        End sub

        public sub DeleteProjectApi(dto As DtoId) Implements IWebApi.DeleteProjectApi

            Dim reqString As byte()

            Using webclient As New WebClient

                dim url as string = "http://localhost/WebApiVB/api/project/DeleteProject"
                webClient.Headers("content-type") = "application/json"
                reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                webClient.UploadData(url, "post", reqString)

            End Using

        End sub
        #End Region

        #Region "Task"

        public function GetTasksByProjIdApi(id as int32) as List(Of DtoTask) Implements IWebApi.GetTasksByProjIdApi

            Dim dtotasks = new List(Of DtoTask)

            dim url = "http://localhost/WebApiVB/api/task/GetTasksByProjectId?id=" & id

            Using webclient As New WebClient
                dim json  = webclient.DownloadString(url)
                Dim tasks = JsonConvert.DeserializeObject(of List(Of DtoTask))(json)
                dtotasks = tasks
            End Using

            Return dtotasks

        End function
        
        public Function  GetTaskByIdApi(id As int32) As DtoTask Implements IWebApi.GetTaskByIdApi

            dim dto as DtoTask

            dim url = "http://localhost/WebApiVB/api/task/GetTaskById?id=" & id

            Using webclient As New WebClient
                dim json  = webclient.DownloadString(url)
                Dim task = JsonConvert.DeserializeObject(of DtoTask)(json)
                dto = task
            End Using

            return dto

        End Function

        public sub CreateTaskApi(dto As DtoTask) Implements IWebApi.CreateTaskApi

            Dim reqString As byte()

            Using webclient As New WebClient

                dim url as string = "http://localhost/WebApiVB/api/task/CreateTask"
                webClient.Headers("content-type") = "application/json"
                reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                webClient.UploadData(url, "post", reqString)

            End Using
          
        End sub
        
        public sub UpdateTaskApi(dto As DtoTask) Implements IWebApi.UpdateTaskApi

            Dim reqString As byte()

            Using webclient As New WebClient

                dim url as string = "http://localhost/WebApiVB/api/task/UpdateTask"
                webClient.Headers("content-type") = "application/json"
                reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                webClient.UploadData(url, "post", reqString)

            End Using
            
        End sub
        
        public sub DeleteTaskApi(dto As DtoId) Implements IWebApi.DeleteTaskApi

            Dim reqString As byte()

            Using webclient As New WebClient

                dim url as string = "http://localhost/WebApiVB/api/task/DeleteTask"
                webClient.Headers("content-type") = "application/json"
                reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                webClient.UploadData(url, "post", reqString)

            End Using

        End sub
        #End Region  
        
        #Region "Cache"

        public Function  GetCacheApi() As DtoCache Implements IWebApi.GetCacheApi

            dim dtocache = new DtoCache()

            dim url = "http://localhost/WebApiVB/api/cache/GetCache"

            Using webclient As New WebClient
                dim json  = webclient.DownloadString(url)
                Dim deserialized = JsonConvert.DeserializeObject(of DtoCacheRoot)(json)

                dtocache.ProjectTypes = deserialized.DtoCache.ProjectTypes
                dtocache.Durations = deserialized.DtoCache.Durations
                dtocache.Statuses = deserialized.DtoCache.Statuses
                dtocache.Resources = deserialized.DtoCache.Resources

            End Using

            return dtocache

        End Function
        #End Region

    End Class
End Namespace

Saturday, March 2, 2019 7:18 AM

You try this code:

string apiUrl = ConfigurationManager.AppSettings["baseurl"] + "/Application.API/api/GroupAPI";
string numb = 5;
HttpWebRequest apiRequest = WebRequest.Create(apiUrl + "/" + numb) as HttpWebRequest;

try
{
    using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
    {
        StreamReader reader = new StreamReader(response.GetResponseStream());
        apiResponse = reader.ReadToEnd();
 
        ResponseAPICallProduct rootObject = JsonConvert.DeserializeObject<ResponseAPICallProduct>(apiResponse);
    }
}
catch (System.Net.WebException ex)
{
    
}

Reference - Web API tutorial


Sunday, March 3, 2019 9:22 AM

Dear mgebhard,I tried that, but unfortunately, still the problem not solved  

Dear yogyogi,I tried what You mention, but in

apiResponse = reader.ReadToEnd();

There is an error on apiResponse because it is not declared,

I changed it to apiRequest but >> cannot implicity type string to System.Net.HttpWebRequest


Sunday, March 3, 2019 6:50 PM

You should learn how to use the 'using' statment.

/en-us/dotnet/csharp/language-reference/keywords/using-statement

<copied>

The using statement ensures that Dispose is called even if an exception occurs within the using block. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

<end>

public void CreateProjectApi(DtoProject dto)
        {
            using (var client = new HttpClient { BaseAddress = new Uri("http://progmgmntcore2api.com") })
            {
                string serailizeddto = JsonConvert.SerializeObject(dto);

                var inputMessage = new HttpRequestMessage
                {
                    Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                };

                inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage message =
                    client.PostAsync("api/project/CreateProject", inputMessage.Content).Result;

                if (!message.IsSuccessStatusCode)
                    throw new Exception(message.ToString());
            }
        }