Web Services 服务 是不是过时了?创建 Web Services 服务实例

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: 本文讨论了WebServices(基于SOAP协议)与WebAPI(基于RESTful)在开发中的应用,回顾了WebServices的历史特点,比较了两者在技术栈、轻量化和适用场景的差异,并分享了使用VB.net开发WebServices的具体配置步骤和疑问。

Web Services 是不是过时了?

今天是兔年最后一天,先给大家拜个早年 。

昨天上午视频面试一家公司需要开发Web Services 服务,这个也没有什么,但还需要用 VB.net 开发。这个是多古老的语言了,让我想起来了 10年 前 写 VBA 的时候,那就写了一个玩玩?


前言

网上百度了下:基础知识大家了解下 :

选择使用 Web Services 还是 Web API 取决于您的具体需求和技术栈。这两者都是用于实现分布式系统和服务的技术,但它们有一些区别。


Web Services:

SOAP (Simple Object Access Protocol): Web Services 常基于 SOAP 协议,这是一种使用 XML 格式进行通信的协议。

协议和标准: Web Services 通常严格遵循一系列协议和标准,如 WSDL (Web Services Description Language) 用于描述服务,UDDI (Universal Description, Discovery, and Integration) 用于服务的发现。

跨语言性: 由于使用了标准化的协议和格式,Web Services 可以在不同平台和语言之间进行通信。


Web API:

RESTful (Representational State Transfer): Web API 常基于 RESTful 架构,使用 JSON 或 XML 进行数据传输。

轻量级: 相对于 Web Services,Web API 更轻量级,通常使用 HTTP 协议进行通信,不像 Web Services 那样依赖较多的协议和标准。

更简单: Web API 更简单易用,通常适合构建基于 HTTP 的轻量级服务,特别是在移动应用和单页应用中。

一、准备工作


上午查了一些资料

需要安装 mysql 数据库 8.0

需要安装 Microsoft Visual Studio Professional 2022 + vb.net

需要安装 IIS 服务

需要安装 mysql-connector-net-8.3.0 库

自己的 系统是 windows 10

好了基本就些就是开发环境了

二、基本配置步骤

1.选择 web 服务 asmx 服务

2.引用 mysql package

下载地址 https://dev.mysql.com/downloads/connector/net/

需要先安装 mysql 驱动

然后选择 dll 应用

最后 本code 使用是网上的 classicmodels 数据库

可以去下载 classicmodels 数据库具体如下


点击:classicmodels

也可以去 下面我的博客资源下载

https://download.csdn.net/download/tomxjc/88685970

用的是 MySQL 8.0


3.web.config 文件加入数据库connectionString

主要就是加入 这段

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>

    <connectionStrings>
    <add name="MySqlConnection"
       connectionString="Server=localhost;Database=classicmodels;User Id=root;Password=123456;"
       providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
  
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />


  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>


在 vb 中调用的语法是

Public connectionString As String = ConfigurationManager.ConnectionStrings("MySqlConnection").ConnectionString

4.然后写一个 select 的方法

 <WebMethod()>
 Public Function QueryDatabase() As String
     Dim result As String = ""
     Try
         Using connection As New MySqlConnection(connectionString)
             connection.Open()
             ' Specify your MySQL query
             Dim query As String = "SELECT * FROM Products where ='Classic Cars'"
             ' Execute the query
             Using command As New MySqlCommand(query, connection)
                 Using reader As MySqlDataReader = command.ExecuteReader()
                     Dim xmlResult As New XmlDocument()

                     ' Create the root element
                     Dim rootElement As XmlElement = xmlResult.CreateElement("Data")
                     xmlResult.AppendChild(rootElement)
                     While reader.Read()
                         ' Create individual data elements
                         Dim dataElement As XmlElement = xmlResult.CreateElement("Item")
                         Dim idElement As XmlElement = xmlResult.CreateElement("productCode")
                         idElement.InnerText = reader("productCode").ToString()
                         dataElement.AppendChild(idElement)
                         Dim nameElement As XmlElement = xmlResult.CreateElement("productName")
                         nameElement.InnerText = reader("productName").ToString()
                         dataElement.AppendChild(nameElement)
                         Dim lineElement As XmlElement = xmlResult.CreateElement("productline")
                         lineElement.InnerText = reader("productline").ToString()
                         dataElement.AppendChild(lineElement)
                         Dim descElement As XmlElement = xmlResult.CreateElement("productDescription")
                         descElement.InnerText = reader("productDescription").ToString()
                         dataElement.AppendChild(descElement)
                         rootElement.AppendChild(dataElement)
                     End While
                     result = xmlResult.OuterXml
                 End Using
             End Using
         End Using
     Catch ex As Exception
         ' Handle exceptions
         result = $"<Error>{ex.Message}</Error>"
     End Try

     Return result
 End Function


验证数据

结果返回是这样,返回是 字符类型,不是应该自动识别的吗?看来是没有XML序列化

5.方法改造 XML序列化

 <WebMethod()>
 Public Function QueryDatabaseXmlSerializer() As XmlDocument
     '这个表代码XML序列化 并返回 XmlDocument 类型
     Dim xmlDoc As New XmlDocument()

     Try
         Using connection As New MySqlConnection(connectionString)
             connection.Open()

             ' Specify your MySQL query
             Dim query As String = "SELECT * FROM Products WHERE productline = 'Classic Cars'"

             ' Execute the query
             Using command As New MySqlCommand(query, connection)
                 Using reader As MySqlDataReader = command.ExecuteReader()
                     Dim items As New List(Of Products)()

                     While reader.Read()
                         ' Create instances of the Item class and populate them
                         Dim item As New Products() With {
                             .productCode = reader("productCode").ToString(),
                             .productName = reader("productName").ToString(),
                             .productline = reader("productline").ToString(),
                             .productDescription = reader("productDescription").ToString()
                         }

                         items.Add(item)
                     End While

                     ' Serialize the list of items to XML
                     Dim serializer As New XmlSerializer(GetType(List(Of Products)))
                     Using writer As XmlWriter = xmlDoc.CreateNavigator().AppendChild()
                         serializer.Serialize(writer, items)
                     End Using
                 End Using
             End Using
         End Using

         Return xmlDoc
     Catch ex As Exception
         ' Handle exceptions
         Dim errorDoc As New XmlDocument()
         errorDoc.LoadXml($"<Error>{ex.Message}</Error>")
         Return errorDoc
     End Try
 End Function


在加入一个类

Public Class Products
    Public Property productCode As String
    Public Property productName As String
    Public Property productDescription As String
    Public Property productline As String
End Class

再验证一下

6.写一个带参数的

<WebMethod()>
Public Function QueryProductByCodeXmlSerializer(productCode As String) As XmlDocument
    Dim xmlDoc As New XmlDocument()
    Try
        Using connection As New MySqlConnection(connectionString)
            connection.Open()
            ' Specify your MySQL query with a parameter
            Dim query As String = "SELECT * FROM Products WHERE productCode = @ProductCode"

            ' Execute the query
            Using command As New MySqlCommand(query, connection)
                ' Add the parameter to the command
                command.Parameters.AddWithValue("@ProductCode", productCode)

                Using reader As MySqlDataReader = command.ExecuteReader()
                    Dim items As New List(Of Products)()

                    While reader.Read()
                        ' Create instances of the Products class and populate them
                        Dim item As New Products() With {
                        .productCode = reader("productCode").ToString(),
                        .productName = reader("productName").ToString(),
                        .productline = reader("productline").ToString(),
                        .productDescription = reader("productDescription").ToString()
                    }

                        items.Add(item)
                    End While

                    ' Serialize the list of items to XML
                    Dim serializer As New XmlSerializer(GetType(List(Of Products)))
                    Using writer As XmlWriter = xmlDoc.CreateNavigator().AppendChild()
                        serializer.Serialize(writer, items)
                    End Using
                End Using
            End Using
        End Using

        Return xmlDoc
    Catch ex As Exception
        ' Handle exceptions
        Dim errorDoc As New XmlDocument()
        errorDoc.LoadXml($"<Error>{ex.Message}</Error>")
        Return errorDoc
    End Try
End Function


验证数据

显示

7.写一个 Insert的方法

mysql 建表

CREATE TABLE `china_city` (
  `citycode` varchar(10) NOT NULL,
  `city` varchar(50) NOT NULL,
  PRIMARY KEY (`citycode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

代码先写了 类

Public Class ChinaCity
    Public Property CityCode As String
    Public Property City As String
End Class
<WebMethod()>
Public Function InsertCity(cityCode As String, cityName As String) As XmlDocument
    Dim errorDoc, successfulDoc As New XmlDocument()
    Try
        Using connection As New MySqlConnection(connectionString)
            connection.Open()

            ' Specify your MySQL insert query
            Dim query As String = "INSERT INTO china_city (citycode, city) VALUES (@CityCode, @CityName)"

            ' Execute the insert query
            Using command As New MySqlCommand(query, connection)
                ' Add parameters to the command
                command.Parameters.AddWithValue("@CityCode", cityCode)
                command.Parameters.AddWithValue("@CityName", cityName)
                ' Execute the insert query
                Dim rowsAffected As Integer = command.ExecuteNonQuery()
                ' Check if the insertion was successful
                If rowsAffected > 0 Then
                    successfulDoc.LoadXml($"<Result>Insertion successful</Result>")
                    Return successfulDoc
                Else
                    errorDoc.LoadXml($"<Error>No rows inserted</Error>")
                    Return errorDoc
                End If
            End Using
        End Using
    Catch ex As Exception
        ' Handle exceptions
        errorDoc.LoadXml($"<Error>{ex.Message}</Error>")
        Return errorDoc
    End Try
End Function

验证数据

8.最后疑问?Web Services 和Web API 那个运用的更广泛呢?

chatGPT 给出了答案


总结

以上源码下载如下https://download.csdn.net/download/tomxjc/88822612

好了,今天就介绍到这里。希望大家喜欢, 一键三连 ,福星高照



相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
3月前
|
开发框架 JSON 中间件
Go语言Web开发框架实践:使用 Gin 快速构建 Web 服务
Gin 是一个高效、轻量级的 Go 语言 Web 框架,支持中间件机制,非常适合开发 RESTful API。本文从安装到进阶技巧全面解析 Gin 的使用:快速入门示例(Hello Gin)、定义 RESTful 用户服务(增删改查接口实现),以及推荐实践如参数校验、中间件和路由分组等。通过对比标准库 `net/http`,Gin 提供更简洁灵活的开发体验。此外,还推荐了 GORM、Viper、Zap 等配合使用的工具库,助力高效开发。
|
5月前
|
中间件 Go
Golang | Gin:net/http与Gin启动web服务的简单比较
总的来说,`net/http`和 `Gin`都是优秀的库,它们各有优缺点。你应该根据你的需求和经验来选择最适合你的工具。希望这个比较可以帮助你做出决策。
216 35
|
11月前
|
XML JSON 数据安全/隐私保护
Web服务
【10月更文挑战第18天】Web服务
186 9
|
6月前
|
XML JSON API
Understanding RESTful API and Web Services: Key Differences and Use Cases
在现代软件开发中,RESTful API和Web服务均用于实现系统间通信,但各有特点。RESTful API遵循REST原则,主要使用HTTP/HTTPS协议,数据格式多为JSON或XML,适用于无状态通信;而Web服务包括SOAP和REST,常用于基于网络的API,采用标准化方法如WSDL或OpenAPI。理解两者区别有助于选择适合应用需求的解决方案,构建高效、可扩展的应用程序。
|
7月前
|
数据采集 Web App开发 API
FastAPI与Selenium:打造高效的Web数据抓取服务 —— 采集Pixabay中的图片及相关信息
本文介绍了如何使用FastAPI和Selenium搭建RESTful接口,访问免版权图片网站Pixabay并采集图片及其描述信息。通过配置代理IP、User-Agent和Cookie,提高爬虫的稳定性和防封禁能力。环境依赖包括FastAPI、Uvicorn和Selenium等库。代码示例展示了完整的实现过程,涵盖代理设置、浏览器模拟及数据提取,并提供了详细的中文注释。适用于需要高效、稳定的Web数据抓取服务的开发者。
355 15
FastAPI与Selenium:打造高效的Web数据抓取服务 —— 采集Pixabay中的图片及相关信息
|
7月前
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
391 7
|
11月前
|
XML JSON 安全
Web服务是通过标准化的通信协议和数据格式
【10月更文挑战第18天】Web服务是通过标准化的通信协议和数据格式
304 69
|
10月前
|
Go UED
Go Web服务中如何优雅平滑重启?
在生产环境中,服务升级时如何确保不中断当前请求并应用新代码是一个挑战。本文介绍了如何使用 Go 语言的 `endless` 包实现服务的优雅重启,确保在不停止服务的情况下完成无缝升级。通过示例代码和测试步骤,详细展示了 `endless` 包的工作原理和实际应用。
212 3
|
10月前
|
JSON Go UED
Go Web服务中如何优雅关机?
在构建 Web 服务时,优雅关机是一个关键的技术点,它确保服务关闭时所有正在处理的请求都能顺利完成。本文通过一个简单的 Go 语言示例,展示了如何使用 Gin 框架实现优雅关机。通过捕获系统信号和使用 `http.Server` 的 `Shutdown` 方法,我们可以在服务关闭前等待所有请求处理完毕,从而提升用户体验,避免数据丢失或不一致。
150 1
|
11月前
|
XML JSON 安全
定义Web服务
【10月更文挑战第18天】定义Web服务
230 12