我使用vb.net实现了一个web服务
方法就像这样
Public Class WebService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function INSERT_NEW(ByVal i As Integer, ByVal f As String) As String
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Try
con.ConnectionString = ConfigurationManager.ConnectionStrings("WebConnectionSTR").ToString
'Dim strMdbPath As String = "C:\Users\Hossein\Documents\Visual Studio 2010\WebSites\WebSite1\"
'Dim strProvider As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
'Dim strDBFile As String = "db.mdb"
cmd.Connection = con
cmd.CommandText = "insert into tb values (" & i & ",'" & f & "')"
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Return "1"
Catch ex As Exception
con.Close()
Return "0"
End Try
End Function
End Class
如果我运行它并调用它
它是有效的但是当我创建一个Windows应用程序时,我遇到了一个未知的问题 因为我在web方法中使用2(整数和字符串)输入参数作为输入参数, INSERT_NEW(byval i as integer,byval f as string)as string
它没有用
Imports wsdl.Myservice
Public Class Form1
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim s As WebServiceSoap = New WebServiceSoapClient
lblAdd.Text = s.INSERT_NEW(txt1.Text, txt2.Text)
End Sub
End Class
但是当我将web方法中的输入参数更改为INTEGER时,它可以正常工作
在Web服务中使用Web方法中的数据类型是一种限制还是我做错了???
我添加了这3张照片,向您展示我得到的确切错误。
答案 0 :(得分:1)
您声明您的webmethod接收Integer和String。所以你应该传递一个Integer和一个String,但是你的代码试图传递两个字符串。您应该尊重webmethod的签名并按预期传递参数
lblAdd.Text = s.INSERT_NEW(Convert.ToInt32(txt1.Text), txt2.Text)
当然,这里我假设txt1.Text中的字符串可以在整数中转换。
说我希望你注意一下代码的一个非常大的问题: 如果恶意用户传递参数f以下字符串
,会发生什么"xxxxx');DELETE FROM tb; --"
它被称为Sql Injection,可能会对您的数据库造成严重破坏。当您收到用户的输入并将其传递给数据库命令时,尝试使用ALWAYS参数化查询
Using con = New OleDbConnection(ConfigurationManager.ConnectionStrings("WebConnectionSTR").ConnectionString)
Using cmd = New OleDbCommand("insert into tb values (?, ?)", con)
Try
con.Open()
cmd.Parameters.AddWithValue("@p1",i)
cmd.Parameters.AddWithValue("@p2",f)
cmd.ExecuteNonQuery()
Return "1"
Catch ex As Exception
Return "0"
End Try
End Using
End Using
答案 1 :(得分:0)
最后我自己找到了答案
导入wsdl.Myservice
Imports System.Reflection
Public Class Form1
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim s As WebServiceSoap = New WebServiceSoapClient
Dim method As MethodInfo = s.GetType().GetMethod("INSERT_NEW")
Dim returnValue As Integer = method.Invoke(s, New Object() {CInt(txt1.Text), txt2.Text})
lblAdd.Text = returnValue
End Sub
结束班