MVC WebApi的两种访问方法

//UserInfoController

using ClassLibrary;

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


namespace WebApiExam.Controllers
{
    public class UserInfoController : ApiController
    {
        // GET: api/UserInfo
        public IEnumerable<UserInfo> Get()
        {
            List<UserInfo> list = new List<UserInfo>();
            list.Add(new UserInfo() { Id = 1, Name = "zhangsan" });
            list.Add(new UserInfo() { Id = 2, Name = "lisi" });
            list.Add(new UserInfo() { Id = 3, Name = "wangwu" });
            return list;
            //return new string[] { "value1", "value2" };
        }


        // GET: api/UserInfo/5
        public string Get(int id)
        {
            return "value";
        }


        // POST: api/UserInfo
        public void Post([FromBody]string value)
        {
        }


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


        // DELETE: api/UserInfo/5
        public void Delete(int id)
        {
        }
    }

}

//客户端访问,只能在本域中

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
<meta charset="utf-8" />


    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script>
        $(function () {
            loadList();
        });
        function loadList() {
            $.ajax({
                type: 'get',
                data: '{}',
                url:'http://localhost:10536/api/UserInfo',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                success: function (list) {
                    listBody = $('#listBody');
                    listBody.empty();
                    $.each(list, function (index,item) {
                        listBody.append('<tr><td>' + item.Id + '</td><td>' + item.Name + '</td></tr>');


                    })
                }

                });
        }
    </script>
</head>
<body>
    <table border="1">
        <tr>
            <th>编号</th>
            <th>姓名</th>
        </tr>
        <tbody id="listBody">


        </tbody>

    </table>
</body>

</html>

//使用HttpClient访问,可以跨域

using ClassLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;


namespace WebApiClient.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.GetAsync("http://localhost:10536/api/UserInfo").Result;

//方法ReadAsAsync(),必须引用项目Packages里面的System.Net.Http.Formatting.dll才可以使用

            var list = response.Content.ReadAsAsync<List<UserInfo>>().Result;
            ViewData.Model = list;
            return View();
        }
    }

}


//Index.cshtml

@model List<ClassLibrary.UserInfo>
@{
    Layout = null;
}


<!DOCTYPE html>


<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <table border="1">
            <tr>
                <th>编号</th>
                <th>名字</th>
            </tr>
            @foreach(ClassLibrary.UserInfo user in Model)
            {
                <tr>
                    <td>@user.Id</td>
                    <td>@user.Name</td>
                </tr>
            }
        </table>
    </div>
</body>
</html>

原文地址:https://www.cnblogs.com/dxmfans/p/9434739.html