1. 程式人生 > >web api(GET請求方法)

web api(GET請求方法)

//控制器裡的方法

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using Newtonsoft.Json;

namespace WebAPI.Controllers
{
    public class UserController : ApiController
    {
        //建立user資料來源list
        private List<Users> _users = new List<Users> {
            new Users{ UserID=1,UserName="周凱",UserEmail="

[email protected]" },
            new Users{ UserID=2,UserName="凱",UserEmail="[email protected]" },
            new Users{ UserID=3,UserName="周",UserEmail="[email protected]" }
        };
        //點選登入時觸發事件
        //存在時間限制
        [AllowAnonymous]
        [HttpGet]
        public string Login(string Account, string Password)
        {
            if (Account.Equals("admin") && Password.Equals("123"))
            {
                FormsAuthenticationTicket ticketObject =
                    new FormsAuthenticationTicket(0, Account, DateTime.Now,
                              DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", Account, Password),
                              FormsAuthentication.FormsCookiePath);
                var result = new { Result = true, Ticket = FormsAuthentication.Encrypt(ticketObject) };
                return JsonConvert.SerializeObject(result);
            }
            else
            {
                var result = new { Result = false };
                return JsonConvert.SerializeObject(result);
            }

        }

        #region Get請求
        //返回一個數組
        [HttpGet]
        public IEnumerable<Users> GetUserByName(string UserName) {
            string userNameparam = HttpContext.Current.Request.QueryString["UserName"];

            return _users.Where(p => string.Equals(p.UserName, userNameparam, StringComparison.OrdinalIgnoreCase));
        }

        [HttpGet]
        public Users GetUserByid(int id) {
            int idParam =Convert.ToInt32( HttpContext.Current.Request.QueryString["id"]);
            var user = _users.FirstOrDefault(p => p.UserID == idParam);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }

        [HttpGet]
        public IEnumerable<Users> GetUserByNameId(string userName, int id)
        {
            string userNameParam = HttpContext.Current.Request.QueryString["userName"];
            int idParam = Convert.ToInt32(HttpContext.Current.Request.QueryString["id"]);
            return _users.Where(p => string.Equals(p.UserName, userNameParam, StringComparison.OrdinalIgnoreCase) && p.UserID== idParam);
        }


        [HttpGet]
        public IEnumerable<Users> Get()
        {
            return _users;
        }

        #endregion

        //user實體類
        public class Users
    {
        public int UserID { get; set; }
        public string UserName { get; set; }
        public string UserEmail { get; set; }
    }
}
}

//////index頁面

 

<form method="post" action="/api/users/register?id=1">


    <div class="row">
        <div class="col-md-5">


            <h2>Test </h2>
            <p>
                <input type="text" id="txtAccount" name="賬號" />
                <input type="text" id="txtPassword" name="密碼" />
                <input type="button" id="btnLogin" value="登陸" />
            </p>

            <p><input type="text" id="txtId" name="id" /> </p>
            <p>
                <input type="button" id="btnGet1" value="Get1" />
                <input type="button" id="btnGet2" value="Get2" />
                <input type="button" id="btnGet3" value="Get3" />
                <input type="button" id="btnGet4" value="Get4" />
            </p>
            <p>
                <input type="button" id="btnGet5" value="Get5" />
                <input type="button" id="btnGet6" value="Get6" />
                <input type="button" id="btnGet7" value="Get7" />
                <input type="button" id="btnGet8" value="Get8" />
                <input type="button" id="btnGet9" value="Get9" />
            </p>
        </div>

    </div>


    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(function () {
            var ticket = "";//登陸後放在某個html裡面,ajax都得帶上

            //點選登入觸發事件
            $("#btnLogin").on("click", function () {
                

                //獲取倆個文字框的值
                var acconunt = $("#txtAccount").val();
                var password = $("#txtPassword").val();
                //注意:data中的變數名和引數儘量要不一樣否則會提示找不到資源
                $.ajax({
                    url: "/api/user/Login",
                    type: "GET",
                    data: { "Account": acconunt, "Password": password },
                    success: function (data) {
                        debugger;
                        var result = JSON.parse(data);
                        if (result.Result) {
                            ticket = result.Ticket;
                            alert(result.Ticket);
                        } else {
                            alert("failed");
                        }
                    },
                    datatype: "json"
                });
            });

            //btnGet1
            $("#btnGet1").on("click", function () {
                $.ajax({
                    url: "/api/user/GetUserByName",
                    type: "GET",
                    data: { "userName": "明凱" },
                    beforeSend: function (xhr) {
                        //傳送ajax請求之前向http的head裡面加入驗證資訊
                        xhr.setRequestHeader('Authorization', 'BasicAuth ' + ticket);
                    },
                    success: function (data) {
                        alert(data[0].UserID);
                        alert( data[0].UserName);
                        alert(  data[0].UserEmail)
                    },
                    datatype: "json"

                });
            })

            //傳遞一個引數
            //btnGet2
            $("#btnGet2").on("click", function () {
                $.ajax({
                    url: "/api/user/GetUserByid",
                    type: "GET",
                    data: { "id": $("#txtId").val() },
                    beforeSend: function (xhr) {
                        //傳送ajax請求之前向http的head裡面加入驗證資訊
                        xhr.setRequestHeader('Authorization', 'BasicAuth ' + ticket);
                    },
                    success: function (data) {
                        debugger;
                        alert(data.UserEmail)
                    },
                    datatype: "json"

                });
            })

             //傳遞兩個引數
            //btnGet3
            $("#btnGet3").on("click", function () {
                $.ajax({
                    url: "/api/user/GetUserByid",
                    type: "GET",
                    data: { "userName": "明凱", "id": $("#txtId").val() },
                    beforeSend: function (xhr) {
                        //傳送ajax請求之前向http的head裡面加入驗證資訊
                        xhr.setRequestHeader('Authorization', 'BasicAuth ' + ticket);
                    },
                    success: function (data) {
                        debugger;
                        alert(data.UserEmail)
                    },
                    datatype: "json"

                });
            })
        })
        
            //btnGet4 無引數
        $("#btnGet4").on("click", function () {//無引數
            $.ajax({
                url: "/api/user/Get",
                type: "get",
                data: "",
                success: function (data)
                {
                    for (var i = 0; i < data.length; i++) {
                        alert(data[i].UserName);
                    }
                },
                datatype: "json"
            });
        });

    </script>


</form>