zoukankan      html  css  js  c++  java
  • web api 文档声明

    namespaceHelloWebAPI.Controllers{
        usingHelloWebAPI.Models;
        usingSystem;
        usingSystem.Collections.Generic;
        usingSystem.Linq;
        usingSystem.Net;
        usingSystem.Net.Http;
        usingSystem.Web.Http;
    
        publicclassProductsController:ApiController
        {
    
            Product[] products =newProduct[] 
            { 
                newProduct{Id=1,Name="Tomato Soup",Category="Groceries",Price=1}, 
                newProduct{Id=2,Name="Yo-yo",Category="Toys",Price=3.75M}, 
                newProduct{Id=3,Name="Hammer",Category="Hardware",Price=16.99M} 
            };
    
            publicIEnumerable<Product>GetAllProducts()
            {
                return products;
            }
    
            publicProductGetProductById(int id)
            {
                var product = products.FirstOrDefault((p)=> p.Id== id);
                if(product ==null)
                {
                    thrownewHttpResponseException(HttpStatusCode.NotFound);
                }
                return product;
            }
    
            publicIEnumerable<Product>GetProductsByCategory(string category)
            {
                return products.Where(
                    (p)=>string.Equals(p.Category, category,
                        StringComparison.OrdinalIgnoreCase));
            }
        }}

    为了让例子保持简单,我们直接把产品存到控制器类里的一个固定数组里。当然,在实际的程序里需要从数据库里查询或者用其它的一些外部数据源。

    控制器定义了三个方法,要么返回单个商品,要么返回一组产品:

    • GetAllProducts 方法返回所有的产品,返回类型为 IEnumerable<Product> 。
    • GetProductById 方法通过ID查询某个产品。
    • GetProductsByCategory 方法返回指定分类的所有产品。

    完事儿了!web API已经能用了。每一个控制器上的方法都对应了一个URI

    控制器方法URI
    GetAllProducts /api/products
    GetProductById /api/products/id
    GetProductsByCategory /api/products/?category=category

    客户端只要通过放松一个HTTP GET请求到URI就可以调用相应的方法。待会儿我们来看看这个映射是怎么做的。但首先我们先把它跑起来试试。

     1.       Web API中包含的方法

    Action

    HTTP method

    Relative URI

    GetAllContact

    GET

    /api/contact

    GetContact

    GET

    /api/contact /id

    GetListBySex

    GET

    /api/contact?sex=sex

    PostContact

    POST

    /api/contact

    PutContact

    PUT

    /api/contact/id

    DeleteContact

    DELETE

    /api/contact/id

  • 相关阅读:
    慈不掌兵,义不行贾,烂好人难成大业!
    克服焦虑
    静态路由汇总(路由聚合)
    OSPF协议介绍及配置 (下)
    OSPF协议介绍及配置 (上)
    我为什么鼓励工程师写blog
    佛弟子有三样东西需要永远保密
    【交换机在江湖】第十三章 VLAN划分篇
    FileZilla Server ftp 服务器下通过alias别名设置虚拟目录(多个分区)
    Java 对象和类
  • 原文地址:https://www.cnblogs.com/fx2008/p/3317070.html
Copyright © 2011-2022 走看看