web api可以提供方便简单可靠的web服务,可以大量的用于不需要提供复杂的soap协议的环境,以简单明了的形式返回数据,在不太复杂的环境中web api可以做为wcf等重级web服务的一种可替代方案

在web世界中常常使用的方法有

GET

Post

PUT

DELETE

在controler中通常约定,方法名以以上get,post,put,delete打头,相关的请求将根据路由规则自动匹配相应的处理方式,如果需要自定义方法名,不希望以GET.Post,Put,Delete等来做为方法名的一部分,需要以在方法前加特性说做说明,如

[HttpGet]

[HttpPost]

[HttpPut]

[HttpDelete]

Views对于WebAPI来说没有太大的用途,Models中的Model主要用于保存Service和Client交互的对象,这些对象默认情况下会被转换为Json格式的数据进行传输,Controllers中的Controller对应于WebService来说是一个Resource,用于提供服务。和普通的MVC一样,Global.asax用于配置路由规则

以下为具体后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using webapi.Models;
namespace webapi.Controllers
{
    public class UserController : ApiController
    {
        public static List<UserInfo> allModeList = new List<UserInfo>() {
          new UserInfo(){ id=1,userName="zhang", password="123"},
          new UserInfo(){ id=2,userName="lishi", password="123456"},
          new UserInfo(){ id=3,userName="wang", password="1234567"}
        };
        public IEnumerable<UserInfo> getAll()
        {
            return allModeList;
        }
        [HttpGet]
        public UserInfo findById(int id)
        {
            return allModeList.Find(p => p.id == id);
        }
        public bool PostNew(UserInfo user)
        {
            try
            {
                allModeList.Add(user);
                return true;
            }
            catch (Exception)
            {

return false;
            }
        }
        [HttpDelete]
        public bool RemoveAll()
        {
            return allModeList.RemoveAll(p=>p.id!=-1) > 0;
        }
        [HttpDelete]
        public bool RemoveItemById(int id)
        {
            return allModeList.Remove(allModeList.Find(p => p.id == id));
        }
        public UserInfo getUserByName(string username)
        {

return allModeList.Find(p => p.userName == username);
        }
        [HttpPut]
        public void updateById(int id,UserInfo model)
        {
            UserInfo userInfoItem = allModeList.Find(p=>p.id==id);
            allModeList.Remove(userInfoItem);
            userInfoItem.userName = model.userName;
            userInfoItem.password = model.password;
            allModeList.Add(userInfoItem);
            
        }
    }
}

前台代码:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    @Scripts.Render("~/bundles/jquery")
    <script type="text/javascript">
        function getAll() {
            $.ajax({
                url: "/api/User/",
                type: 'GET',
                success: function (data) {
                    document.getElementById("modes").innerHTML = ""
                    $.each(data, function (key, val) {
                       
                        str = val.id + ":    " + val.userName + "   :   " + val.password
                        $('<li/>', { html: str }).appendTo($('#modes'))
                       
                       
                        console.log(key)
                    })
                }
            }).fail(function (xhr, textStatus, err) {
                alert('error'+err)
            })
        }
        function find() {
            $.ajax({
                url: '/api/User/1',
                type: 'GET',
                success: function (data) {
                    document.getElementById("modes").innerHTML = ""
                       str = data.userName + "   :   " + data.password
                        $('<li/>', { html: str }).appendTo($('#modes'))
                   
                }
            }).fail(function (xhr, textstatus, err) {
                    alert('Error Info'+err)
            })
        }
        function add() {
            $.ajax({
                url: "/api/user/",
                type: "POST",
                dataType: "json",
                data: { 'id': 4, 'userName': 'test1', 'password': 'Pass@word' },
                success: function (data) {
                    getAll()
                }
            }).fail(function (xhr, textstatus, err) {
                alert("error"+err)
            })
        }
        function removeAll()
        {
            $.ajax({
                url: '/api/user/',
                type: 'DELETE',
                success: function (data) {
                    getAll()
                }
            }).fail(function (xhr,textstatus,err) {
                alert('error'+err)
            })
        }

function removeUser() {
            $.ajax({
                url: '/api/user/1',
                type: 'DELETE',
                success: function (data) {
                    getAll()
                }
            }).fail(function (xhr, textstatus, err) {

alert("error"+err)
            })
        }
        function getUserByName()
        {
            $.ajax({
                url: '/api/user?username=zhang',
                type: 'GET',
                success: function (data) {
                    str=data.userName+":   "+data.password
                    $('<li/>', { html: str }).appendTo($('#modes'))
                    console.log(data)
                }
            })
        }
        function udpate()
        {
            $.ajax({
                url: '/api/user/2',
                type: 'PUT',
                dataType: 'json',
                data: { Id: 2, "userName": "admin", "password": "666666" },
                success: function (data) {
                    getAll()
                }
            }).fail(function (xhr, textstatus, err) {
                    alert('error'+err)
            })
        }
    </script>
</head>
<body>
    <div>
        <button onclick="getAll()">getAll</button>
        <button onclick="find()">find</button>
        <button onclick="add()">add</button>
        <button onclick="removeUser()">remove</button>
        <button onclick="removeAll()">removeAll</button>
        <button onclick="udpate()">udpate</button>
        <button onclick="getUserByName()">getUserByName</button>
     
    </div>
    <div id="modes">

</div>
</body>
</html>
运行结果 :

.net web api 一的更多相关文章

  1. 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用

    由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...

  2. bootstrap + requireJS+ director+ knockout + web API = 一个时髦的单页程序

    也许单页程序(Single Page Application)并不是什么时髦的玩意,像Gmail在很早之前就已经在使用这种模式.通常的说法是它通过避免页面刷新大大提高了网站的响应性,像操作桌面应用程序 ...

  3. Hello Web API系列教程——Web API与国际化

    软件国际化是在软件设计和文档开发过程中,使得功能和代码设计能处理多种语言和文化习俗,在创建不同语言版本时,不需要重新设计源程序代码的软件工程方法.这在很多成熟的软件开发平台中非常常见.对于.net开发 ...

  4. ASP.NET Web API 跨域访问(CORS)

    一.客户端用JSONP请求数据 如果你想用JSONP来获得跨域的数据,WebAPI本身是不支持javascript的callback的,它返回的JSON是这样的: {"YourSignatu ...

  5. Web Api 入门实战 (快速入门+工具使用+不依赖IIS)

    平台之大势何人能挡? 带着你的Net飞奔吧!:http://www.cnblogs.com/dunitian/p/4822808.html 屁话我也就不多说了,什么简介的也省了,直接简单概括+demo ...

  6. Web APi之认证(Authentication)两种实现方式【二】(十三)

    前言 上一节我们详细讲解了认证及其基本信息,这一节我们通过两种不同方式来实现认证,并且分析如何合理的利用这两种方式,文中涉及到的基础知识,请参看上一篇文中,就不再叙述废话. 序言 对于所谓的认证说到底 ...

  7. angular2系列教程(八)In-memory web api、HTTP服务、依赖注入、Observable

    大家好,今天我们要讲是angular2的http功能模块,这个功能模块的代码不在angular2里面,需要我们另外引入: index.html <script src="lib/htt ...

  8. 我这么玩Web Api(二):数据验证,全局数据验证与单元测试

    目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试   一.模型状态 - ModelState 我理解 ...

  9. 我这么玩Web Api(一):帮助页面或用户手册(Microsoft and Swashbuckle Help Page)

    前言 你需要为客户编写Api调用手册?你需要测试你的Api接口?你需要和前端进行接口对接?那么这篇文章应该可以帮到你.本文将介绍创建Web Api 帮助文档页面的两种方式,Microsoft Help ...

  10. [译] 在Web API 2 中实现带JSON的Patch请求

    原文链接:The Patch Verb in Web API 2 with JSON 我想在.NET4.6 Web API 2 项目中使用Patch更新一个大对象中的某个字断,这才意识到我以前都没有用 ...

随机推荐

  1. TCP/IP系列——长连接与短连接的区别

    1 什么是长连接和短连接       三次握手和四次挥手   TCP区别于UDP最重要的特点是TCP必须建立在可靠的连接之上,连接的建立和释放就是握手和挥手的过程. 三次握手为连接的建立过程,握手失败 ...

  2. document.write 存在几个问题?应该注意

    document.write (henceforth DW) does not work in XHTML XHTML 不支持 DW executed after the page has finis ...

  3. MongoDb笔记(一)

    1.Mongodb 数据库是动态生成的可以使用use 数据库名 来指定要使用的数据库,如果数据库不存在就自动生成一个 2.插入一个文档:db.foo.insert({"name": ...

  4. 对list代理扩展功能

    package 动态代理扩展List; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; imp ...

  5. scrollview不能滚动

    1. 图片视图上不能直接滚动,需要设置交互属性为YES _contentView = [[UIImageView alloc]initWithFrame:CGRectMake(0, _headerVi ...

  6. java web移植 遇到Project facet Java version 1.7 is not supported

    在移植eclipse项目时,如果遇到 "Project facet Java version 1.7 is not supported." 项目中的jdk1.7不支持.说明项目是其 ...

  7. 13年山东省赛 The number of steps(概率dp水题)

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud The number of steps Time Limit: 1 Sec  Me ...

  8. perl6之'Hello World'

    安装完perl6之后,当然是要写一下Hello World了. 因为perl6的脚本一般都很短小,所以用不着很笨重的IDE之类的东西,我们用VIM,sublime text这种小型的编辑器 来开始pe ...

  9. GO语言基础

    Go语言开发 一.Linux下搭建Go开发环境 首先下载Go语言的开发安装包,不管是在官方网站或者国内的Golang镜像都是可以的,注意区分64位和32位的安装包. 下载完安装包之后tar zxvf进 ...

  10. 关于Mysql不能被远程连接的问题

    1.修改mysql配置文件 注释掉   #bind_address:127.0.0.1 2.授权账户远程连接权限 grant all priveleges on '.' To 'myuser'@'%' ...