//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. [tmux] Copy and paste text from a tmux session

    One non-obvious, but extremely useful, feature in tmux is copy-pasting text between panes. This also ...

  2. 断言(Assert)与异常(Exception)

    ## 断言和异常 断言是用来检查非法情况而不是错误情况的,用来帮开发者快速定位问题的位置. 异常处理用于对程序发生异常情况的处理,增强程序的健壮性和容错性. ## 断言的使用 在防御式编程中经常会用断 ...

  3. php正则怎么使用(最全最细致)

    php正则怎么使用(最全最细致) 一.总结 一句话总结: 1.正则中的行定位符是什么? 解答:(^与$) 2.正则中什么时候用行定位符? 解答:如"^de",表示以de开头的字符串 ...

  4. erlang中变量作用域

    http://erlangdisplay.iteye.com/blog/315452 _开头(包括_)在erlang可以是表明,这个变量可以存任意东西,就是我们常说的全匹配,_A一般来说就是表明这个东 ...

  5. erlang lists

    http://blog.csdn.net/dp0304/article/details/7590233 一,带函数Pred1, all(Pred, List) -> boolean()如果Lis ...

  6. 【14.67%】【codeforces 615D】Multipliers

    time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...

  7. selenium firefox 提取qq空间相册链接

    环境: selenium-java 3.9.1 firefox 57.0 geckodriver 0.19.1 1.大概的思路就是模拟用户点击行为,关于滚动条的问题,我是模拟下拉箭头,否则只能每个相册 ...

  8. Java入门程序

    JavaC.exe 编译器,编译.java文件 Java.exe 解释器,执行class文件 编译命令  javac HelloWorld.java 编译后 会产生同名的.class文件 javac编 ...

  9. React Native细节记录

    1.环境搭建部分 安装完node后建议设置npm镜像以加速后面的过程(或使用***工具).注意:不要使用cnpm!cnpm安装的模块路径比较奇怪,packager不能正常识别! npm config ...

  10. android 流量统计

    1 android通过架构流量统计TrafficStats类可以直接获得     获得总流量受理TrafficStats.getTotalRxBytes(),     获得总传出流量TrafficSt ...