zoukankan      html  css  js  c++  java
  • 【翻译】ASP.NET Web API入门

    简介

    ASP.NET Web API是一个可以简化创建HTTP服务的框架

    它支持包括浏览器和移动设备在内的各种客户端

    ASP.NET Web API是在.NET Framework上创建RESTful应用程序的理想平台

    译者注:关于RESTful web服务可以参见这里:http://zh.wikipedia.org/wiki/REST

    准备

    ASP.NET MVC 4包括ASP.NET Web API,请在这里安装:http://www.asp.net/web-api

    使用Visual Studio 2010或者Visual Studio 2012都可以开发

    关于ASP.NET Web API的特性请看这里:http://www.asp.net/whitepapers/mvc4-release-notes#_Toc317096197

    简介

    HTTP并不是单单为web pages服务的

    它还是一个创建网络API的强大平台

    这些API提供网络服务并可以交互数据。

    HTTP协议简单、灵活最重要的是它无处不在

    差不多你能想到的所有的平台都支持HTTP协议

    所以通过HTTP协议可以兼容大部分客户端

    包括浏览器、移动客户端和桌面应用

    ASP.NET Web API是一个在.NET Framework上创建web API的类库

    在这篇文章中,

    你将看到如何使用ASP.NET Web API创建一个web api,

    并且让这个api返回一个产品列表的数据

    新建项目

    如下图所示:

    image

    image

    创建模型

    模型是一个用来展现数据的对象

    ASP.NET WEB API可以自动序列化模型对象

    为JSON、XML、或者其他的数据格式

    然后把序列化后的数据写入HTTP的Response消息内

    客户端可以读取这些序列化后的数据

    并把这些数据反序列化成一个对象

    大多数客户端可以解析XML,JSON数据

    并且可以根据消息的header来决定使用什么格式化数据的方式

    image

    创建一个名为Product的模型类

    代码如下

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace HelloWebAPI.Models
    {
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Category { get; set; }
            public decimal Price { get; set; } 
        }
    }

    创建控制器

    如果你使用过ASP.NET MVC

    你会发现ASP.NET WEB API的控制器

    与ASP.NET MVC的控制器基本相同

    最大的不同就是

    ASP.NET WEB API的控制器继承自ApiController

    ASP.NET MVC的控制器继承自Controller

    WEB API的控制器并不返回View,而是直接返回数据。

    image

    image

    并不一定要把所创建的控制器类文件放在Controller文件夹中

    创建的文件,修改之后代码如下

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using HelloWebAPI.Models;
    
    namespace HelloWebAPI.Controllers
    {
        public class ProductsController : ApiController
        {
            Product[] products = new Product[]  
            {  
                new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1.39M },  
                new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },  
                new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }  
            };
    
            public IEnumerable<Product> GetAllProducts()
            {
                return products;
            }
    
            public Product GetProductById(int id)
            {
                var product = products.FirstOrDefault((p) => p.Id == id);
                if (product == null)
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.NotFound);
                    throw new HttpResponseException(resp);
                }
                return product;
            }
    
            public IEnumerable<Product> GetProductsByCategory(string category)
            {
                return products.Where(
                    (p) => string.Equals(p.Category, category,
                        StringComparison.OrdinalIgnoreCase));
            }
        }
    
    }

    GetAllProducts方法返回一个Product类型的数组

    GetProductById通过ID查找Product

    GetProductsByCategory通过分类查找Product

    至此

    你可以通过如下URI访问相应的方法

    GetAllProducts:/api/products

    GetProductById:/api/products/id

    GetProductsByCategory:/api/products/?category=category

    访问WEB API

    运行此工程,

    访问如下URL可以得到结果

    http://localhost:5380/api/products

    image

    这里我们看到的是XML的内容

    但WEB API非常智能

    可以通过客户端的请求来确定传输什么类型的数据

    我们可以通过如下代码来获取JSON类型的数据

       $(document).ready(function () {
                    // Send an AJAX request 
                    $.getJSON("api/products/",
                    function (data) {
                        // On success, 'data' contains a list of products. 
                        $.each(data, function (key, val) {
    
                            // Format the text to display. 
                            var str = val.Name + ': $' + val.Price;
    
                            // Add a list item for the product. 
                            $('<li/>', { html: str })
                            .appendTo($('body'));
                        });
                    });
                });

    获取到的数据如下图所示

    image

    原文地址:http://www.jianfangkk.com/aspnet/201511/293

  • 相关阅读:
    大学总结(一)
    关于数组名与指针的相互转换
    错误:无法执行操作,因为未将指定的 Storyboard 应用到此交互控件的对象
    延迟初始化 (Lazy Initialization)
    Sql Server 中 GAM、SGAM、PAM、IAM、DCM 和 BCM 的详解与区别
    Xml格式的字符串(string)到DataSet(DataTable)的转换
    Sql Server 内存用不上的解决办法
    Sql Server 管理区分配(GAM,SGAM)和可用空间(PAM)的原理
    Sql Server LightWeight Pooling(纤程) 选项
    在线 Sql Server 服务无法启动的解决办法
  • 原文地址:https://www.cnblogs.com/jianfangkk/p/5107966.html
Copyright © 2011-2022 走看看