//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>

MVC WebApi的两种访问方法的更多相关文章

  1. js对象的 两种访问方式

    来对象访问属性有两种方式.有一个对象Obj = {"Name":"Langshen","AGE":"28"} 用点访问, ...

  2. bind()函数的深入理解及两种兼容方法分析

    在JavaScript中,bind()函数仅在IE9+.Firefox4+.Chrome.Safari5.1+可得到原生支持.本文将深入探讨bind()函数并对两种兼容方法进行分析比较.由于本文将反复 ...

  3. angular2系列教程(十)两种启动方法、两个路由服务、引用类型和单例模式的妙用

    今天我们要讲的是ng2的路由系统. 例子

  4. git两种合并方法 比较merge和rebase

    18:01 2015/11/18git两种合并方法 比较merge和rebase其实很简单,就是合并后每个commit提交的id记录的顺序而已注意:重要的是如果公司用了grrit,grrit不允许用m ...

  5. 两种Ajax方法

    两种Ajax方法 Ajax是一种用于快速创建动态网页的技术,他通过在后台与服务器进行少量的数据交换,可以实现网页的异步更新,不需要像传统网页那样重新加载页面也可以做到对网页的某部分作出更新,现在这项技 ...

  6. mysql in 的两种使用方法

    简述MySQL 的in 的两种使用方法: 他们各自是在 in keyword后跟一张表(记录集).以及在in后面加上字符串集. 先讲后面跟着一张表的. 首先阐述三张表的结构: s(sno,sname. ...

  7. C#中的两种debug方法

    这篇文章主要介绍了C#中的两种debug方法介绍,本文讲解了代码用 #if DEBUG 包裹.利用宏定义两种方法,需要的朋友可以参考下   第一种:需要把调试方法改成debug代码用 #if DEBU ...

  8. Service的两种启动方法

    刚才看到一个ppt,介绍service的两种启动方法以及两者之间的区别. startService 和 bindService startService被形容为我行我素,而bindService被形容 ...

  9. jQuery ajax调用后台aspx后台文件的两种常见方法(不是ashx)

    在asp.net webForm开发中,用Jquery ajax调用aspx页面的方法常用的有两种:下面我来简单介绍一下. [WebMethod] public static string SayHe ...

随机推荐

  1. [React] Update State in React with Ramda's Evolve

    In this lesson we'll take a stateful React component and look at how we can refactor our setState ca ...

  2. php课程 5-18 数组排序和合并拆分函数有哪些

    php课程  5-18   数组排序和合并拆分函数有哪些 一.总结 一句话总结:分类来记.这些函数自己都可以写,费点时间而已. 1.array_combine()和array_merge()的区别是什 ...

  3. 详解PHP设置定时任务的实现方法

    详解PHP设置定时任务的实现方法 一.总结 一句话总结: 1.ignore_user_abort(true)是什么意思? 无论客户端是否关闭浏览器,下面的代码都将得到执行 2.set_time_lim ...

  4. 学习鸟哥的Linux私房菜笔记(16)——Ubuntu中建立ftp服务

    1.安装vsftpd,如下图所示:sudo apt-get install vsftpd 2.查看本机是否可以连接ftp 如上图所示,发现login failed了,怎么办呢?我们来看看vsftpd的 ...

  5. NOIP模拟 path - 按二进制位分组

    题目原文: 企鹅豆豆即将要去考长跑了,但是作为一只企鹅,长跑自然比不过鸵鸟和鸡.为了公平起见,教练告诉豆豆,他可以从 K 个指定地点中选择两个不同的地点分别作为起点和终点来考试.考试地图是一个由 N ...

  6. cordova 生成发行版apk,并添加证书 – 畅玩Coding

    原文:cordova 生成发行版apk,并添加证书 – 畅玩Coding 首先jdk生成证书. 1.进入jdk安装目录 D:\Java\jdk1.7.0\bin 2.执行命令 keytool -gen ...

  7. JS高级程序设计拾遗

    <JavaScript高级程序设计(第三版)>反反复复看了好多遍了,这次复习作为2017年上半年的最后一次,将所有模糊的.记不清的地方记录下来,方便以后巩固. 0. <script& ...

  8. 通过javacv对视频每隔1秒钟截取1张图片

    Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org. ...

  9. QImage学习学习

    QImage这个类之前用过,无外乎是加载一个图片文件显示出来,并没有做过多的研究,目前工作中用到了灰度图以及图片的像素操作,重新学习了下,记录记录. 一些基本操作方法 获取图像的首地址: const ...

  10. 放大缩小,只需要使用这2个函数:SetWindowExtEx、SetViewportExtEx

    相似函数: ScaleWindowExtEx.ScaleViewportExtEx 本例效果图: 代码文件: unit Unit1; interface uses   Windows, Message ...