Web API 简单示例

简介: 原文:Web API 简单示例一、RESTful和Web API   Representational State Transfer (REST) is a software architecture style consisting of guidelines and best practices for creating scalable web services.
原文: Web API 简单示例

一、RESTfulWeb API

  Representational State Transfer (REST) is a software architecture style consisting of guidelines and best practices for creating scalable web services. REST is a coordinated set of constraints applied to the design of components in a distributed hypermdedia system that can lead to a more performant and maintainable architecture.  -- wikipedia 

  ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

  原来RESTful是一种软件架构风格(REST是一种设计风格,而不是一种标准),而ASP.NET Web API是其在.NET平台的一种标准/实现。目前在三种主流的Web Services实现方案中,因为REST模式与复杂的SOAPXML -PRC相比更加简洁,越来越多的web服务开始采用REST风格设计和实现。

  ASP.NET整体框架结构如下图。可以看出,Web API支持JSONXML,面向的是多种客户终端,包括多浏览器和各种移动设备。

 

二、简单示例

   新建ASP.NET Web Application,命名NBAApp

  

  选择Empty模板,下面选择Web API,更改AuthenticationNo Authentication

 

  新建一个Model - Player 

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

namespace NBAApp.Models
{
    public class Player
    {
        public int Id { get; set; }
        public int No { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public string Team { get; set; }
    }
}

 

  新建Controller - PlayersController,模板选择Web API 2 Controller - Empty

  

  编辑代码如下

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

namespace NBAApp.Controllers
{
    public class PlayersController : ApiController
    {
        Player[] players = new Player[] { 
            new Player { Id = 1, No = 3, Name = "Chris Paul", Position = "Point Guard", Team = "Los Angeles Clippers" },
            new Player { Id = 2, No = 3, Name = "Dwyane Wade", Position = "Shooting Guard", Team = "Miami Heat" },
            new Player { Id = 3, No = 23, Name = "LeBron James", Position = "Forward", Team = "Cleveland Cavaliers" },
            new Player { Id = 4, No = 21, Name = "Tim Duncan", Position = "Power forward", Team = "San Antonio Spurs" },
            new Player { Id = 5, No = 33, Name = "Marc Gasol", Position = "Center", Team = "Memphis Grizzlies" }
        };

        public IEnumerable<Player> GetAllPlayers()
        {
            return players;
        }

        public IHttpActionResult GetPlayer(int id)
        {
            var player = players.FirstOrDefault<Player>(p => p.Id == id);
            if (player == null)
            {
                return NotFound();
            }
            return Ok(player);
        }
    }
}

 

  添加Html - Index.html页面

 

  编辑代码如下

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>NBA App</title>
</head>
<body>

    <div>
        <h2>All Players</h2>
        <ul id="players" />
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="prodId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="player" />
    </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
        var uri = 'api/players';

        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON(uri)
                .done(function (data) {
                    // On success, 'data' contains a list of players.
                    $.each(data, function (key, item) {
                        // Add a list item for the player.
                        $('<li>', { text: formatItem(item) }).appendTo($('#players'));
                    });
                });
        });

        function formatItem(item) {
            return item.Id + ": " + item.Name + "(" + item.No + ')' + " - " + item.Team + "(" + item.Position + ")";
        }

        function find() {
            var id = $('#prodId').val();
            $.getJSON(uri + '/' + id)
                .done(function (data) {
                    $('#player').text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#player').text('Error: ' + err);
                });
        }
    </script>
</body>
</html>

 

  执行效果如下(Chrome浏览器)

 

  F12调出Developer Tools,点击红点Recording Network Log,刷新页面,结果如下

 

  点击进去,并选择Response标签,可以清楚地看到传输交换的是JSON格式的字符

 

 

代码下载

NBAApp

目录
相关文章
|
1月前
|
JSON API 数据库
解释如何在 Python 中实现 Web 服务(RESTful API)。
解释如何在 Python 中实现 Web 服务(RESTful API)。
26 0
|
2月前
|
IDE Java API
使用Java Web技术构建RESTful API的实践指南
使用Java Web技术构建RESTful API的实践指南
|
16天前
|
JSON 监控 API
在API接口对接中关键示例问题(1)
在API接口对接中,有几个关键的问题需要注意,以确保接口的稳定性、安全性和易用性。以下是这些问题及部分示例代码的简要概述
|
1月前
|
XML JSON API
通过Flask框架创建灵活的、可扩展的Web Restful API服务
通过Flask框架创建灵活的、可扩展的Web Restful API服务
|
1月前
|
Java API PHP
获取1688商品详情API:步骤与代码示例
在电子商务领域,阿里巴巴的1688平台是一个广受商家和开发者欢迎的批发交易市场。若您是一名开发者,希望建立自己的应用程序或网站来获取并展示1688上的商品信息,您可能需要使用到1688提供的API接口。以下是获取1688商品详情API的详细步骤说明。
|
1月前
|
缓存 监控 API
Python Web框架FastAPI——一个比Flask和Tornada更高性能的API框架
Python Web框架FastAPI——一个比Flask和Tornada更高性能的API框架
58 0
|
1月前
|
JSON API 数据格式
构建高效Python Web应用:Flask框架与RESTful API设计实践
【2月更文挑战第17天】在现代Web开发中,轻量级框架与RESTful API设计成为了提升应用性能和可维护性的关键。本文将深入探讨如何使用Python的Flask框架来构建高效的Web服务,并通过具体实例分析RESTful API的设计原则及其实现过程。我们将从基本的应用架构出发,逐步介绍如何利用Flask的灵活性进行模块化开发,并结合请求处理、数据验证以及安全性考虑,打造出一个既符合标准又易于扩展的Web应用。
653 4
|
1月前
|
Java API
Java 日期和时间 API:实用技巧与示例 - 轻松处理日期和时间
简介 Scanner 类用于获取用户输入,它位于 java.util 包中。 使用 Scanner 类 要使用 Scanner 类,请执行以下步骤: 导入 java.util.Scanner 包。 创建一个 Scanner 对象,并将其初始化为 System.in。 使用 Scanner 对象的方法读取用户输入。
54 1
|
2月前
|
前端开发 JavaScript API
前端秘法番外篇----学完Web API,前端才能算真正的入门
前端秘法番外篇----学完Web API,前端才能算真正的入门
|
2月前
|
API 网络架构
解释 RESTful API,以及如何使用它构建 web 应用程序。
解释 RESTful API,以及如何使用它构建 web 应用程序。
88 0