Return Data Table from ASP.NET WEB API in C#

Return C# DataTable : Web API Tutorial

In this session we will learn…
How to Consume WEB API using HttpClient
Return C# DataTale from WEB API
Important point is DeserializeObject and SerializeObject
Using Visual Studio 2012
Correct Name Space is Required

Related Videos:




Add the folowing method In ASP.NET WebApplication to call and consume the webapi
public DataTable GetTableData(string id)
        {
            using (WebAPIServiceClient = new HttpClient())
            {
                #region Consume GET method
                WebAPIServiceClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["WebAPIServiceUrl"].ToString());
                WebAPIServiceClient.DefaultRequestHeaders.Accept.Clear();
                WebAPIServiceClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                response = WebAPIServiceClient.GetAsync("api/values/GetDataTable?id=" + id).Result;
                if (response.IsSuccessStatusCode)
                {
                    string jsonString = response.Content.ReadAsStringAsync().Result;
                    _dt=(DataTable)JsonConvert.DeserializeObject(jsonString,(typeof(DataTable)));
                }
                else
                {
                    Message = "Internal server Error with API";
                }
            }       
            #endregion
            return _dt;
        }

Add the folowing method In ASP.NET WebAPI to respond to web application
[HttpGet]
        public JsonResult<DataTable> GetDataTable(string id)
        {
            DataTable table = new System.Data.DataTable();
            table.Columns.Add("Dosage", typeof(int));
            table.Columns.Add("Drug", typeof(string));
            table.Columns.Add("Patient", typeof(string));
            table.Columns.Add("Date", typeof(DateTime));
            table.Rows.Add(25, "Indocin", "Sam", DateTime.Now);
            table.Rows.Add(27, "Indocin", "David", DateTime.Now);
            table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
            table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
            table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
            table.Rows.Add(23, "Combivent", "steav", DateTime.Now);
            table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
            return Json(table);
        }

If any error, try these.

  • Assembly Newtonsoft.Json.dll, v9.0.0.0
  • Assembly System.Web.Http.dll, v5.2.7.0
  • PM> Install-Package Microsoft.AspNet.WebApi.Core -Version 5.2.7
  • PM> install-package Microsoft.AspNet.WebApi.HelpPage
  • Update-Package -ProjectName 'YourProjectNameGoesHere' -Reinstall


Next : WEB API Credential in Request Header

No comments:

Post a Comment

Your feedback is important.
Visit www.techwebdots.in