Wednesday 4 January 2017

Create a Web Api Service and call it in to Asp.net Project.

First Create a Web Api project. Net Add a Controller. in this Controller. you Write. Add a Layer which name is Data Access Layer. Next add a Web Application with a Page which name is Default.aspx.


 public class TestController : ApiController
    {
        MyModelEntities db = new MyModelEntities();
        // GET: api/Test
        Class1 cl = new Class1();
        public HttpResponseMessage Get()
        {
            var v = (from c in cl.getdata() select
                         new demo{
                         Id=c.Id.ToString(),
                         Contact_Id = c.Contact_Id.ToString(),
                         Contact_Name=c.Contact_Name
                         }).ToList();

            return new HttpResponseMessage()
            {
                Content = new StringContent(JArray.FromObject(v).ToString(), Encoding.UTF8, "application/Json")
            };
        }
        public class demo
        {
            public string Id { get; set; }
            public string Contact_Id { get; set; }
            public string Contact_Name { get; set; }

            public string City { get; set; }
        }
        // GET: api/Test/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Test
        public HttpResponseMessage Post([FromBody]string name)
        {
            DataAccessLayer.tbl_Contact tcc = new DataAccessLayer.tbl_Contact();
            tcc.Contact_Name = name;
            cl.insertData(tcc);
            //return obj;
            var v = (from c in cl.getdata()
                     select
                         new demo
                         {
                             Id = c.Id.ToString(),
                             Contact_Id = c.Contact_Id.ToString(),
                             Contact_Name = c.Contact_Name
                         }).ToList();
            return new HttpResponseMessage()
            {
                Content = new StringContent(JArray.FromObject(v).ToString(), Encoding.UTF8, "application/Json")
            };
        }

        // PUT: api/Test/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Test/5
        public HttpResponseMessage Delete(int id)
        {

            DataAccessLayer.tbl_Contact tcc = new DataAccessLayer.tbl_Contact();
            tcc.Id = id;
            cl.DeleteData(tcc);
            //return obj;
            var v = (from c in cl.getdata()
                     select
                         new demo
                         {
                             Id = c.Id.ToString(),
                             Contact_Id = c.Contact_Id.ToString(),
                             Contact_Name = c.Contact_Name
                         }).ToList();
            return new HttpResponseMessage()
            {
                Content = new StringContent(JArray.FromObject(v).ToString(), Encoding.UTF8, "application/Json")
            };
        }



     
    }
=====================================================
 In DataAccess Layer
====================================================
 public partial class Class1
    {
        InductionNewEntities db = new InductionNewEntities();
        public  IEnumerable<tbl_Contact> getdata()
        {
            var v = from c in db.tbl_Contact select c;

            string data = "";
            return v.ToList();
        }


        public tbl_Contact insertData(tbl_Contact obj)
        {
            using (var ve = new InductionNewEntities())
            {
                tbl_Contact tc = new tbl_Contact();
                tc.Contact_Name = obj.Contact_Name;
                ve.tbl_Contact.Add(tc);
                ve.SaveChanges();
                return obj;
            }
        }
        public tbl_Contact DeleteData(tbl_Contact obj)
        {
            using (var ve = new InductionNewEntities())
            {
                tbl_Contact tc = db.tbl_Contact.Where(t=> t.Id==obj.Id).First();

                db.tbl_Contact.Remove(tc);
                db.SaveChanges();
                return obj;
            }
        }
    }
================================================

In Asp.net Project
==============================================
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button id="btn_post" runat="server" Text="Post" OnClick="btn_post_Click"/>
    <asp:Button id="btn_get" runat="server" Text="Get" OnClick="btn_get_Click"/>
        <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Id">
                    <ItemTemplate>
                        <asp:Label ID="lbl_id" runat="server" Text='<%# Eval("Id") %>' ></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lbl_ContactName" runat="server" Text='<%# Eval("Contact_Name") %>' ></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="ContactId">
                    <ItemTemplate>
                        <asp:Label ID="lbl_ContactId" runat="server" Text='<%# Eval("Contact_Id") %>' ></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:Button Text="Delete" runat="server" CommandArgument='<%# Eval("Id") %>' ID="btn_del" OnClick="btn_del_Click"  />
                    </ItemTemplate>

                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
===============================================
C# Code in Web Page
===============================================
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using DataAccessLayer;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {

         
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            { 
            
            }
        }
        public  List<demo> demoList = new List<demo>();
        public  class demo
        {
            public string Id { get; set; }
            public string Contact_Id { get; set; }
            public string Contact_Name { get; set; }
        }
        
        protected void btn_post_Click(object sender, EventArgs e)   
         {
             HttpClient client = new HttpClient();
             client.BaseAddress = new Uri("http://localhost:49504/");

             // Add an Accept header for JSON format.
             client.DefaultRequestHeaders.Accept.Add(
                 new MediaTypeWithQualityHeaderValue("application/json"));

             var user = new demo();

             user.Contact_Name = txt_name.Text;

             var response = client.PostAsJsonAsync("api/Test", txt_name.Text).Result;

             if (response.IsSuccessStatusCode)
             {
                 Response.Write("User Added");

                 getdata();
             }
             else
             {
                 Response.Write("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
             }
        }
        public void getdata()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:49504/");

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

            HttpResponseMessage response = client.GetAsync("api/Test").Result;

            if (response.IsSuccessStatusCode)
            {
                var users = response.Content.ReadAsAsync<IEnumerable<demo>>().Result;

                //usergrid.ItemsSource = users;
                GridView1.DataSource = users.ToList();
                GridView1.DataBind();
            }
            else
            {
                //MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
                Response.Write("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
            }
        }
        protected void btn_get_Click(object sender, EventArgs e)
        {
            getdata();
        }

        protected void btn_del_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            int id = Convert.ToInt32(btn.CommandArgument);

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:49504/");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            var user = new demo();

            user.Contact_Name = txt_name.Text;

            var url = "api/Test/" + id;

            HttpResponseMessage response = client.DeleteAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                Response.Write("User Deleted ");
                getdata();
            }
            else
            {
                Response.Write("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
            }
        }


    }
}

No comments:

Post a Comment