• 我的第一个webapiDemo


           最近在面试,总是被问到有没有接触过webapi 或者问webapi和MVC 的区别,今天看了看,原来如此,自己理解感觉webapi和webservice一样像是实现soa 的一种形式,也可以理解为服务或者是一种数据请求框架

           下面简单的写一下我第一个webapi 实例过程。

           软件环境:vs2012 

           1、创建ASP.NET MVC4 Web 项目->点击ok->在“新ASP.NET MVC 4项目”对话框中,选择“Web API”并点击“OK”.

                                       

          2、Add a model. 名为Product.cs. 赋几个属性,代码为          

    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; }
        }
    }

          3、Add a controller.名为ProductsController.(创建控制器时,模板选择空API控制器),然后实现方法,如下namespace HelloWebAPI.Controllers

    {
        using HelloWebAPI.Models;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Net;
        using System.Net.Http;
        using System.Web.Http;
        public class ProductsController : ApiController
        {
    //为了保持示例简单,产品被存储在该控制器类的一个固定数组中。当然,在一个实际应用程序中,你会查询一个数据库,或使用某些其它外部数据源。 Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } };
    //无参Get方法 返回产品列表 public IEnumerable<Product> GetAllProducts() { return products; }
    //参数为id的Get方法 返回单个产品 public Product GetProductById(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return product; }
    //参数为category的Get方法 public IEnumerable<Product> GetProductsByCategory(string category) { return products.Where( (p) => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)); } } }

       4、现在我们就有了一个可以工作的webapi ,控制器上每一个方法都映射到一个Url上,如下:

                   

          5、通过浏览器调用api   ie浏览器会下载json 文件 firefox 则会显示为xml格式,如下:

               IE:  

           Firefox:

         6、现在试着浏览下面两个URL:

    • http://localhost:xxxx/api/products/1
    • http://localhost:xxxx/api/products?category=hardware

         第一个应当返回ID等于1的词条。第二个应当返回Category等于“hardware”的所有产品的列表(这里,只有一个词条)。

         7、现在以一个前台页面调用API为例,找到View下面的Home->Index.cshtml文件,写入如下代码:         

    • <!DOCTYPE html> <html lang="en"> <head> <title>ASP.NET Web API</title> <link href="~/Content/Site.css" rel="stylesheet" /> <script src="~/Scripts/jquery-1.7.1.min.js"></script> </head> <body id="body" > <div class="main-content"> <div> <h1>All Products</h1> <ul id="products"/> </div> <div> <label for="prodId">ID:</label> <input type="text" id="prodId" size="5"/> <input type="button" value="Search" onclick="find();" /> <p id="product" /> </div> </div> </body> <script type="text/javascript"> //getJSON()和get是一样的,都是get请求,这就决定了,发送的data数据量不能太多,否则造成url太长接收失败(getJSON方式是不可能有post方式递交的)。 //区别是,getJSON专门请求json数据的,而且getJSON可以实现跨域请求 $(document).ready(function () { // Send an AJAX request // 发送AJAX请求 $.getJSON("api/products/", function (data) { // On success, 'data' contains a list of products. // 成功时,'data'含有一组产品列表 $.each(data, function (key, val) { // Format the text to display. // 格式化文本,以便显示 var str = val.Name + ': $' + val.Price; // Add a list item for the product. // 添加一个产品列表项 $('<li/>', { text: str }) .appendTo($('#products')); }); }); //$.post("api/products/",{id:"123",name:"小明"},function(data){ // $.each(data, function (key, val) { // // Format the text to display. // // 格式化文本,以便显示 // var str = val.Name + ': $' + val.Price; // // Add a list item for the product. // // 添加一个产品列表项 // $('<li/>', { text: str }) // .appendTo($('#products')); // }); // },"json") // }); function find() { var id = $('#prodId').val(); $.getJSON("api/products/" + id, function (data) { var str = data.Name + ': $' + data.Price; $('#product').text(str); }) .fail( function (jqXHR, textStatus, err) { $('#product').text('Error: ' + err); }); } </script> </html>

        8、直接运行,得到如下页面:

                      

              表明我们的HTTP服务已经在工作。你可以在文本框中输入ID并通过这个ID获得一个产品。

            

           9、理解路由         

              对于每一个HTTP消息,ASP.NET Web API框架都会通过咨询一个路由表来决定接收该请求的控制器。在创建一个新的Web API项目时,该项目便会包含一个类似于下面这 样的默认路由:

    /api/{controller}/{id}

    {controller}{id}部分是占位符。当框架看到一个与此模式匹配的URI时,它按以下步骤查找控制器方法:
      • {controller}用来匹配控制器名
      • HTTP请求的方法用来匹配方法名。(此规则仅适用于GET、POST、PUT和DELETE请求。)
      • {id},如果有,用来匹配名称为id的方法参数。
      • 可能的情况下,查询参数用来匹配参数名。

                   

                其中第一个示例,“products”匹配名为ProductsController的控制器。该请求是一个GET请求,因此框架在ProductsController上查找一个名称以“GET…”开头的方法。进一步地,这个URI不包含可选的{id}片段,因此,框架查找的是一个不带参数的方法。于是,ProductsController->GetAllProducts满足所有这些需求。

                第二个示例与此相同,只是该URI包含了{id}选项。因此,框架会调用GetProduct,它有一个名称为id的参数。另外,这个URI的值“5”会作为这个id参数的值进行传递。框架会根据该方法的签名,自动地把这个“5”转换成int类。

             这只是个简单的Demo,个人目前只理解到这么多,希望能运用到更多更好的项目中,可以更加熟练。

  • 相关阅读:
    Redux基础使用
    react native 第三方组件react-native-swiper 轮播组件
    React native中的组建通知通信:
    更新:在MAC上安装RN开发环境的步骤(全)
    React Native组件之BackAndroid !安卓手机的物理返回键的使用
    使用redux简单的实现加法运算(简单的状态改变)
    【HTML+JavaScript(jQuery)】实现侧边栏下拉菜单
    第四章 前端开发——JQuery库
    【HTML+CSS+JavaScript】实现地址选择联动
    【HTML+CSS+JavaScript】实现待办事项(纯DOM实现)
  • 原文地址:https://www.cnblogs.com/KarenLiu/p/lxmPearlLady_net_webapiDemo.html
Copyright © 2020-2023  润新知