zoukankan      html  css  js  c++  java
  • ServiceStack Web Service 创建与调用简单示列

    上篇文章介绍了ServiceStack是什么,本章进入主题,如何快速简单的搭建ServiceStack服务环境和调用。

    ServiceStack服务搭建

    服务的搭建有两种方法,我会一一介绍。

    第一种方法如下:

    1.创建网站项目

    2.安装发布组件

    packages.confing文件为您提供每一个ServiceStack dll 的版本和运行时信息。

    定义是 ServiceStack <Ticket> 请求数据契约

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using ServiceStack;
    
    namespace Model
    {
        /// <summary>
        /// 创建票据 请求实体
        /// </summary>
        public class TicketRequest : IReturn<TicketResponse>
        {
            public int TicketId { get; set; }
            public int TableNumber { get; set; }
            public int ServerId { get; set; }
        }
        public class TicketDeleteRequest
        {
            public int TicketId { get; set; }
        }
    }

    定义ServiceStack <Ticket> 响应数据契约

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Model
    {
        /// <summary>
        /// 创建票据响应数据实体
        /// </summary>
        public class TicketResponse
        { 
            public int TicketId { get; set; }
            public int TableNumber { get; set; }
            public int ServerId { get; set; }
            public List<OrderResponse> Orders { get; set; }
            public DateTime Timestamp { get; set; }
        }
        /// <summary>
        /// 票据所属订单
        /// </summary>
        public class OrderResponse
        {
            public int OrderId { get; set; }
        }
    }

    定义ServiceStack 接口方法

    using Model;
    using System.Collections.Generic;
    
    namespace Interface
    {
        public interface ITicketService
        {
            /// <summary>
            /// 方法请求模式和路由规则 后面再说
            /// 请求票据列表
            /// </summary>
            /// <param name="request"></param>
            /// <returns></returns>
            List<TicketResponse> Any(TicketRequest request);
            /// <summary>
            /// 删除指定票据
            /// </summary>
            /// <param name="request"></param>
            /// <returns></returns>
            bool POST(TicketDeleteRequest deleteid);
        }
    }

    实现ServiceStack 接口方法

    using Interface;
    using Model;
    using System;
    using System.Collections.Generic;
    
    namespace Service
    {
        public class TicketService : ServiceStack.Service, ITicketService
        {
            /// <summary>
            /// 方法请求模式和路由规则 后面再说
            /// 请求票据列表
            /// </summary>
            /// <param name="request"></param>
            /// <returns></returns>
            public List<TicketResponse> Any(TicketRequest request)
            {
                List<TicketResponse> result = new List<TicketResponse>();
                List<OrderResponse> orderlist = new List<OrderResponse>();
                orderlist.Add(new OrderResponse() { OrderId = 1 });
                result.Add(new TicketResponse()
                {
                    Orders = orderlist,
                    ServerId = 1,
                    TableNumber = 1,
                    TicketId = 1,
                    Timestamp = DateTime.Now
                });
                result.Add(new TicketResponse()
                {
                    Orders = orderlist,
                    ServerId = 2,
                    TableNumber = 2,
                    TicketId = 2,
                    Timestamp = DateTime.Now
                });
    
                return result;
            }
            /// <summary>
            /// 删除指定票据
            /// </summary>
            /// <param name="request"></param>
            /// <returns></returns>
            public bool POST(TicketDeleteRequest deleteid)
            {
                return true;
            }
        }
    }

    实现ServiceStack服务宿主

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Service.Host
    {
        public class TickServiceHost : ServiceStack.AppHostBase
        {
            // Register your Web service with ServiceStack.
            public TickServiceHost()
                : base("Ticket Service", typeof(Service.TicketService).Assembly) { }
            public override void Configure(Funq.Container container)
            {
                // Register any dependencies your services use here.
            }
        }
    }

    启动ServiceStack服务宿主

    <%@ Application Language="C#" %>
    
    <script runat="server">
    
        void Application_Start(object sender, EventArgs e) 
        {
            // 在应用程序启动时运行的代码
            new Service.Host.TickServiceHost().Init();
        }
        
        void Application_End(object sender, EventArgs e) 
        {
            //  在应用程序关闭时运行的代码
    
        }
            
        void Application_Error(object sender, EventArgs e) 
        { 
            // 在出现未处理的错误时运行的代码
    
        }
    
        void Session_Start(object sender, EventArgs e) 
        {
            // 在新会话启动时运行的代码
    
        }
    
        void Session_End(object sender, EventArgs e) 
        {
            // 在会话结束时运行的代码。 
            // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
            // InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
            // 或 SQLServer,则不引发该事件。
    
        }
           
    </script>

    添加ServiceStack网站集成配置

    <?xml version="1.0" encoding="utf-8"?>
    
    <!--
      有关如何配置 ASP.NET 应用程序的详细信息,请访问
      http://go.microsoft.com/fwlink/?LinkId=169433
      -->
    
    <configuration>
    
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
      </system.web>
      <!--Required for IIS 7 (and above) -->
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
          <add path="*.aspx" name="DefaultHttpApplication" type="System.Web.UI.PageHandlerFactory" verb="*" />
          <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true"/>
        </handlers>
      </system.webServer>
    </configuration>

    至此ServiceStack服务已经完成,运行程序可以看到界面如下,其中TicketRequest和TicketDeleteRequest可以理解成实际的调用方法,里面定义的参数可以理解成方法的请求参数,后续调用会继续讲解

    整个项目解决方案的框架如下:

    第二种创建方法比较简单,快速,利用ServiceStack官方提供的模板直接生成,具体操作方法如下:

    1.打开VS,工具扩展和更新

    2.搜索servicestack提供的组件

    3.安装完成后创建新项目,来自模板

    创建完成后的项目框架如下

    5.改成我们所需要的

     ServiceStack客户端调用

    using ConsoleApplication1.model;
    using ServiceStack;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                //客户端采用json数据格式
                JsonServiceClient client1 = new JsonServiceClient("http://localhost:32617/");
                Console.WriteLine("http://localhost:32617/");
                //TicketRequest 为请求的方法
                List<TicketResponse> responseSearch = client1.Get<List<TicketResponse>>(new TicketRequest() { TicketId = 1 });
                Console.WriteLine(responseSearch.Count);
    
                bool responseDelete = client1.Post<bool>(new TicketDeleteRequest() { TicketId = 1 });
                Console.WriteLine(responseDelete);
    
                Console.WriteLine("http://localhost:36107/");
    
                List<TicketResponse> responseSearch1 = client1.Get<List<TicketResponse>>(new TicketRequest() { TicketId = 1 });
                Console.WriteLine(responseSearch1.Count);
    
                bool responseDelete1 = client1.Post<bool>(new TicketDeleteRequest() { TicketId = 1 });
                Console.WriteLine(responseDelete1); 
                  
                Console.ReadLine();
            }
        }
    }

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1.model
    {
        /// <summary>
        /// 创建票据 请求实体
        /// IReturn<TicketResponse> 指该方法返回的数据实体
        /// </summary>
        public class TicketRequest
        {
            public int TicketId { get; set; }
            public int TableNumber { get; set; }
            public int ServerId { get; set; }
        }
        public class TicketDeleteRequest
        {
            public int TicketId { get; set; }
        }
    }

    浏览器端调用:

     

    请求URL如下:

    浏览器输入http://localhost:36107/json/reply/TicketRequest?TicketId=1

    浏览器默认请求为GET,如果方法定义POST请求类型,可以采用第三方模拟Rest请求工具

    参考: 

    https://servicestack.net/features

    https://msdn.microsoft.com/zh-cn/magazine/dn342871.aspx

    http://www.cnblogs.com/shanyou/p/3348347.html

    http://www.cnblogs.com/yangecnu/p/Introduce-ServiceStack.html

  • 相关阅读:
    fadeIn()与fadeOut()方法
    js常用正则表达式(经典)
    正则表达式大全
    slideDown()和slideUp()方法
    toggle()显示/隐藏的用法
    skip-grant-tables 修改linux的mysql忘记root密码
    基于Vue、web3的以太坊项目开发及交易内幕初探 错误解决总结
    MySQL linux错误处理
    求职 firekylin
    如何编写一个可升级的智能合约
  • 原文地址:https://www.cnblogs.com/happyyftk/p/6904998.html
Copyright © 2011-2022 走看看