ASP.Net: WebApi คืนค่าและรับค่าเป็นคลาส

  1. คืนค่าเป็นคลาส
  2. รับค่าเป็นคลาส
    • ทดลองส่งค่าไปด้วย Postman
    • ทดลองส่งค่าไปด้วย ASP.NET
    • ทดลองส่งค่าไปด้วย WebForm

1.คืนค่าเป็นคลาส

แก้ไข Controllers > ValuesController.cs

ing System.Collections.Generic;
using System.Web.Http;

namespace WebApi1.Controllers
{
    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class ValuesController : ApiController
    {
        // GET api/values
        public List<Person> Get()
        {
            List<Person> people = new List<Person>{
                   new Person{ID = 1, FirstName = "Phaisarn", LastName = "Sutheebanjard"},
                   new Person{ID = 2, FirstName= "Foo", LastName = "Bar"}
                   };
            return people;
        }

        // GET api/values/5
        public Person Get(int id)
        {
            Person person = new Person
            {
                ID = 1,
                FirstName = "Phaisarn",
                LastName = "Sutheebanjard"
            };
            return person;
        }
    }
}

บรรทัดที่ 6-15: สร้างคลาส Person
บรรทัดที่ 16: กำหนดให้คืนค่าเป็น List<Person>
บรรทัดที่ 18-21: สร้างตัวแปร people พร้อมกำหนดค่าให้
บรรทัดที่ 22: คืนค่า people

ลองเรียกไปที่ http://localhost:57067/api/Values จะได้

[
    {
        "ID": 1,
        "FirstName": "Phaisarn",
        "LastName": "Sutheebanjard"
    },
    {
        "ID": 2,
        "FirstName": "Foo",
        "LastName": "Bar"
    }
]

จากหน้า ASP.NET Web API Help Page เมื่อคลิกดูที่ GET api/Values จะได้

และถ้าลองเรียกไปที่ http://localhost:57067/api/Values/5 จะได้

{
    "ID": 1,
    "FirstName": "Phaisarn",
    "LastName": "Sutheebanjard"
}

2.รับค่าเป็นคลาส

แก้ไข Controllers > ValuesController.cs

using System.Collections.Generic;
using System.Web.Http;

namespace WebApi1.Controllers
{
    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class ValuesController : ApiController
    {
        // GET api/values
        public List<Person> Get()
        {
            List<Person> people = new List<Person>{
                   new Person{ID = 1, FirstName = "Phaisarn", LastName = "Sutheebanjard"},
                   new Person{ID = 2, FirstName= "Foo", LastName = "Bar"}
                   };
            return people;
        }

        // GET api/values/5
        public Person Get(int id)
        {
            Person person = new Person
            {
                ID = 1,
                FirstName = "Phaisarn",
                LastName = "Sutheebanjard"
            };
            return person;
        }

        // POST api/values
        public string Post([FromBody]Person param)
        {
            return param.ID + " " +
                param.FirstName + " " +
                param.LastName;
        }
    }
}

2.1 ทดลองส่งค่าไปด้วย Postman

ตัวอย่างค่าที่ใช้ส่ง

{
    "ID": 1,
    "FirstName": "Phaisarn",
    "LastName": "Sutheebanjard"
}

ค่าที่ได้กลับมา

"1 Phaisarn Sutheebanjard"

2.2 ทดลองส่งค่าไปด้วย ASP.NET

using System;
using System.IO;
using System.Net;

namespace WebApp2
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            string url = "http://localhost:59425/api/values";

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"ID\": 1," +
                "\"FirstName\": \"Phaisarn\"," +
                "\"LastName\": \"Sutheebanjard\"}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }            
        }
    }
}

2.3 ทดลองส่งค่าไปด้วย WebForm

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>

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

<body>
    <form id="myform" name="myform" method='POST'
        runat="server">
        <p>
            <asp:TextBox ID="ID" Text="" runat="server"></asp:TextBox>
        </p>
        <p>
            <asp:TextBox ID="FirstName" Text="" runat="server"></asp:TextBox>
        </p>
        <p>
            <asp:TextBox ID="LastName" Text="" runat="server"></asp:TextBox>
        </p>
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
        <p>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </p>
    </form>
</body>
</html>

WebForm1.aspx.cs

using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

namespace WebApp2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        
        protected void Button1_Click(object sender, EventArgs e)
        {          
            string url = "http://localhost:59425/api/Values";

            try
            {
                WebClient client = new WebClient();

                // Upload some form post values.
                NameValueCollection form = new NameValueCollection();
                form.Add("ID", ID.Text);
                form.Add("FirstName", FirstName.Text);
                form.Add("LastName", LastName.Text);
                Byte[] responseData = client.UploadValues(url, form);
         
                // Decode and display the response.
                Console.WriteLine();
                Label1.Text = "Response received was :" + Encoding.ASCII.GetString(responseData);
            }
            catch (WebException webEx)
            {
                Console.WriteLine(webEx.ToString());
                if (webEx.Status == WebExceptionStatus.ConnectFailure)
                {
                    Label1.Text = "Something to wrong.";
                }
            }
        }
    }
}

ถ้าต้องการให้โหลดข้อมูลเสร็จแล้ว POST อัตโนมัติ ให้ดูที่นี่