zoukankan      html  css  js  c++  java
  • ASP.NET---如何使用web api创建web服务

    1 首先创建asp.net web空项目,并且创建模拟数据,我在工程下面创建了一个Models文件夹,在文件夹Nodels下面创建类Product和Repository

     具体如下:

     [Serializable]
        public class Product
        {
            public int ProductID { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public decimal Price { get; set; }
            public string Category { get; set; }
        }
    public class Repository
        {
            private static Dictionary<int, Product> data = new Dictionary<int, Product>();
    
            static Repository()
            {
                Product[] dataArray = new Product[]
                {
                    new Product {Name="Kayak",Category="watersports",Price=275M },
                    new Product {Name="lifejacket",Category="watersports",Price=48.95M },
                    new Product {Name="Soccer Ball",Category="Soccer",Price=19.50M },
                    new Product {Name="corner flags",Category="Soccer",Price=34.94M },
                    new Product {Name="Stadium",Category="Soccer",Price=795000M },
                    new Product {Name="thinking cap",Category="Chess",Price=16M },
                    new Product {Name="unsteady chair",Category="Chess",Price=29.95M },
                    new Product {Name="human chess board",Category="Chess",Price=75M },
                    new Product {Name="Bling-Bling King",Category="Chess",Price=1200M },
                };
                for (int i = 0; i < dataArray.Length; i++)
                {
                    dataArray[i].ProductID = i;
                    data[i] = dataArray[i];
                }
            }
    
            public IEnumerable<Product> Products
            {
                get
                {
                    return data.Values;
                }
            }
    
            public void SaveProduct(Product pro)
            {
    
                data[pro.ProductID] = pro;
    
            }
    
            public void DeleteProduct(Product pro)
            {
                if (data.ContainsKey(pro.ProductID))
                {
                    data.Remove(pro.ProductID);
                }
            }
    
            public void AddProduct(Product pro)
            {
                pro.ProductID = Products.Select(p => p.ProductID).Max() + 1;
                SaveProduct(pro);
            }
        }
    2 asp.net4.5引入了web api功能,可以通过该功能创建简单,轻量级,仿效http的web服务,从而使用各种http方法(get,put,post,delete等)指定不同的
    数据操作,这是表述性状态转移(rest)风格的web API基础。通常称为rest服务,即通过URL以及用于请求他的http方法指定某项操作
    3 web API服务一般遵循/api/<datatype>这一web api约定
    4 如何创建web 服务
    要创建web服务,需要使用web api controller class(web api 控制器类)项模板在visual studio项目中添加一个新项,web api控制器的一个默认约定是
    web api类的名称应该是web服务处理的数据类型名称与controller一词的组合,那么我这个示例就是ProductController
    创建成功后如下所示:
      public class ProductController : ApiController
        {
            // GET api/<controller>
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // GET api/<controller>/5
            public string Get(int id)
            {
                return "value";
            }
    
            // POST api/<controller>
            public void Post([FromBody]string value)
            {
            }
    
            // PUT api/<controller>/5
            public void Put(int id, [FromBody]string value)
            {
            }
    
            // DELETE api/<controller>/5
            public void Delete(int id)
            {
            }
        }
    
    

    5 创建路由的配置

      为啥要创建路由:默认情况下,web API 控制器处于不可用的状态,因此必须使用URL路由功能在URL与类之间建立映射关系。因此,我在示例项目下创建App_Start文件夹,并在其中添加RouteConfig类文件,并定义控制器类ProductController所需的路由

     public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.MapHttpRoute(name: "WebApiRoute",
                    routeTemplate: "api/{controller}/id",
                    defaults: new { id = RouteParameter.Optional });
            }
        }

    这是为控制器类创建的路由,需要引用system.web.http命名空间,最后需要在全局应用程序类中注册路由,以便在应用程序启动时初始化URL路由

     在实例中添加全局应用程序类

    public class Global : System.Web.HttpApplication
        {
    
            protected void Application_Start(object sender, EventArgs e)
            {
                RouteConfig.RegisterRoutes(RouteTable.Routes);
            }
    
            protected void Session_Start(object sender, EventArgs e)
            {
    
            }
    
            protected void Application_BeginRequest(object sender, EventArgs e)
            {
    
            }
    
            protected void Application_AuthenticateRequest(object sender, EventArgs e)
            {
    
            }
    
            protected void Application_Error(object sender, EventArgs e)
            {
    
            }
    
            protected void Session_End(object sender, EventArgs e)
            {
    
            }
    
            protected void Application_End(object sender, EventArgs e)
            {
    
            }
        }

    6 接下来就可以测试创建的web api了

    启动应用程序输入URL:http://localhost:59288/api/product结果如下:

     7 下面我们创建asp.net web form来进行测试

       首先需要添加jquery文件jquery-3.2.1.js到项目中,然后再在测试的webform窗体中引用它,测试窗体的前台代码如下:

      

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ProductTest.aspx.cs" Inherits="WebAPIServer.ProductTest" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
            div {
                margin-bottom:10px;
            }
        </style>
        <script src="Script/jquery-3.2.1.js"></script>
        <script type="text/javascript">
            function GetObjectString(dataObject)
            {
                if (typeof dataObject=="string") {
                    return dataObject;
                }
                else {
                    var message = "";
                    for (var prop in dataObject) {
                        message += prop + ":" + dataObject[prop] + "
    ";
                    }
                    return message;
                }
            }
    
            $(document).ready(function () {
                $("button").click(function (e) {
                    var action = $(e.target).attr("data-action");
                    $.ajax(
                         {
                             //设置ajax请求的url
                             url: action == "all" ? "/api/product" : "/api/product/1",
                             //设置请求的http方式
                             type: "GET",
                             //设置请求的数据类型
                             datatype: "json",
                             //设置在ajax请求成功时调用的函数,次函数传递从web服务中检索到的数据
                             success: function (data)
                             {
                                 debugger;
                                 if (Array.isArray(data)) {
                                     var message = "";
                                     for (var i = 0; i < data.length; i++) {
                                         message += "Item" + [i] + "
    "
                                         + GetObjectString(data[i]) + "
    
    ";
                                     }
                                     $("#results").text(message);
                                 }
                                 else {
                                     $("#results").text(GetObjectString(data));
                                 }
                             }
                         });
                    e.preventDefault();
                });
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <button data-action="all">Get all</button>
                <button data-action="one">Get one</button>
            </div>
            <textarea id="results" cols="40" rows="10">
    
            </textarea>
        </form>
    </body>
    </html>

    点击get all 发送ajax请求,就会调用webapi控制器中的get无参数方法显示结果如下:

    这个就是我创建的web API get无参数方法返回的结果

    接下来就是对象序列化的问题开源的Json.NET程序包支持这种特性。

  • 相关阅读:
    【转】直方图中bins的理解及处理
    [LeetCode] 1. Two Sum
    数据结构课学到的常用知识总结概括
    Java核心技术第三章数据类型
    mysql 出现You can't specify target table for update in FROM clause错误的解决方法
    mysql 从一个表中查数据并插入另一个表实现方法
    使用ECharts,绘制柱状图
    mysql 查询1小时内_mysql查询一个小时之内的数据
    mysql查询表中所有字段的名字
    MySQL 时间函数总集
  • 原文地址:https://www.cnblogs.com/mibing/p/7838779.html
Copyright © 2011-2022 走看看