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

  • 相关阅读:
    Python 异常处理
    汉语分词软件的使用 (python底下)
    谈谈python的文件处理——文件的输入与输出
    统计翻译系统中的开源工具们
    研究生如何选定课题方向 如何变学神
    口语翻译——AI过程的必经之路
    google的盈利模式
    机器翻译软件从实验室走向市场
    I'm Back
    jquery getJSON
  • 原文地址:https://www.cnblogs.com/fx2008/p/3317070.html
Copyright © 2011-2022 走看看