❶ 如何用c語言實現基於http的webservice
package com.yun.test;
import java.rmi.RemoteException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.PrefixedQName;
import org.apache.axis.message.SOAPHeaderElement;
import com.cezanne.golden.user.Exception;
import com.cezanne.golden.user.UserManagerServiceProxy;
import javax.xml.namespace.QName;
import java.net.MalformedURLException;
import javax.xml.rpc.ServiceException;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPException;
public class testWebService {
public static String getResult() throws ServiceException, MalformedURLException, RemoteException, SOAPException
{
//標識Web Service的具體路徑
String endpoint = "WebService服務地址";
// 創建 Service實例
Service service = new Service();
// 通過Service實例創建Call的實例
Call call = (Call) service.createCall();
//將Web Service的服務路徑加入到call實例之中.
call.setTargetEndpointAddress( new java.net.URL(endpoint) );//為Call設置服務的位置
// 由於需要認證,故需要設置調用的SOAP頭信息。
Name headerName = new PrefixedQName( new QName("發布的wsdl里的targetNamespace里的url", "string_itemName") );
org.apache.axis.message.SOAPHeaderElement header = new SOAPHeaderElement(headerName);
header.addTextNode( "blablabla" );
call.addHeader(header);
// SOAPHeaderElement soapHeaderElement = new SOAPHeaderElement("發布的wsdl里的targetNamespace里的url", "SoapHeader");
// soapHeaderElement.setNamespaceURI("發布的wsdl里的targetNamespace里的url");
// try
// {
// soapHeaderElement.addChildElement("string_itemName").setValue("blablabla");
// }
// catch (SOAPException e)
// {
// e.printStackTrace();
// }
// call.addHeader(soapHeaderElement);
//調用Web Service的方法
org.apache.axis.description.OperationDesc oper;
org.apache.axis.description.ParameterDesc param;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("opName");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "arg0"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName(", "string"), java.lang.String.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "arg1"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName(", "string"), java.lang.String.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "arg2"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName(", "string"), java.lang.String.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName(", "string"));
oper.setReturnClass(java.lang.String.class);
oper.setReturnQName(new javax.xml.namespace.QName("", "return"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("發布的wsdl里的targetNamespace里的url", "Exception"),
"Exception",
new javax.xml.namespace.QName("發布的wsdl里的targetNamespace里的url", "Exception"),
true
));
call.setOperation( oper );
call.setOperationName(new javax.xml.namespace.QName("發布的wsdl里的targetNamespace里的url", "opName"));
//調用Web Service,傳入參數
String res = ( String ) call.invoke( new Object[]("arg0","arg1"));
System.out.println("===============");
return res;
}
/**
* @param args
*/
public static void main(String[] args) {
try {
System.out.println(getResult());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
} catch (SOAPException e) {
e.printStackTrace();
}
}
}
❷ 如何在C++中使用WebService
使用gsoap生成所需的WebService
下載後的gsoap包為:
將他解壓後,進入到文件夾:gsoap_2.8.18\gsoap-2.8\gsoap\bin\win32
裡面有2個我們要用到的exe,wsdl2h.exe和soapcpp2.exe,如果缺少一個typemap.dat,則從gsoap_2.8.18\gsoap-2.8\gsoap下拷貝進來,最後就可以啟用cmd,開始生成WebService了
我的做法是拷貝一個cmd的快捷方式進來,然後右鍵屬性,把它的「起始位置」設置為F:\webSite\gsoap_2.8.18\gsoap-2.8\gsoap\bin\win32,應用後啟動此快捷方式,那麼操作目錄就為當前目錄了。利用wsdl2h.exe,使用cmd生成WebService的頭文件如下:
wsdl2h -o 頭文件名 WSDL文件名或URL
說明:(注意大小寫)
-o 文件名,指定輸出頭文件名
-n 命名空間前綴 代替默認的ns
-c 產生純C代碼,否則是C++代碼
-s 不要使用STL代碼
-t 文件名,指定type map文件,默認為typemap.dat
-e 禁止為enum成員加上命名空間前綴
這里我生成一個foxwelltech.h頭文件,不使用STL,結果如下:
生成的foxwelltech.h就包含了所有預先寫好的WebService函數介面。從cmd中可以看到該命令需要用到typemap.dat文件,所以如果沒有該文件,會提示找不到文件,需要從別處拷貝過來。接下來,我們按照cmd最後的提示,進行下一步,用soapcpp2.exe來生成可用的.h和.cpp文件:
soapcpp2常用選項:(注意大小寫)
-C 僅生成客戶端代碼
-S 僅生成伺服器端代碼
-L 不要產生soapClientLib.c和soapServerLib.c文件
-c 產生純C代碼,否則是C++代碼(與頭文件有關)
-I 指定import路徑(見上文)
-x 不要產生XML示例文件
-i 生成C++包裝,客戶端為xxxxProxy.h(.cpp),伺服器端為xxxxService.h(.cpp)
如果報錯:Critical error: #import: Cannot open file "stlvector.h"for reading.
Hint: use option -I<path> (you candefine multiple paths separated with ';')
則要使用-I選項指定gSOAP的 import文件路徑
我使用的命令行是:
soapcpp2 -C -x foxwelltech.h -IF:\Website\gsoap_2.8.18\gsoap-2.8\gsoap\import
意為根據foxwelltech.h只生成客戶端代碼,不生成無用的xml文件,另外要引用一個import文件夾,結果如下:
最後的Compilation successful說明了一切,結果就是生成了一個nsmap命名空間文件,二個.h文件,三個.cpp文件
最後,我們新建一個C++的控制台工程來使用它們
注意:
1. 第一步生成的foxwelltech.h不用加進來,直接使用由它生成的後續.h和.cpp即可
2. stdsoap2.h和stdsoap2.cpp來自於路徑:F:\Website\gsoap_2.8.18\gsoap-2.8\gsoap
3. 除nsmap文件外,其他6個都要添加到工程裡面編譯,然後添加測試代碼
❸ WebService編程
基於webservice編程,可以把軟體的復用提高到整個Internet這個層面上,如果你有個應用程序通過WebService發布,那麼不僅僅是公司內部可用(可以是其他的C/S或者B/S的應用程序),其他連到Internet上的公司也可以使用。屏蔽了不同語言之間的差異。因為底層是Http協議,所以可以輕松穿越企業防火牆
webservice 是一種技術也是一種規范(比如WebService必須用WSDL描述)
就是在Http上公開一些方法(服務)讓別人使用。
跟資料庫沒有直接關系。
❹ C/C++實現WebService服務提供JSON數據的介面
1、C++可以實現webservice,這是毋庸置疑的.axis2本質是運行在tomcat下的一個servlet,分java版本,和C語言版本.官方網站為:http://axis.apache.org/,首頁上寫著:
The well known Apache Axis, and the the second generation of it, the Apache Axis2, are two Web Service containers that helps users to create, deploy, and run Web Services.Axis2 is avaialble in both Java as well as C, languages and details about each version can be found below. 大概意思就是這東西分java版本和C版本,可以方便用戶創建,部署,運行web service.而C++完全是兼容C的.
2、需要伺服器,要實現某個服務吧,至於怎樣為其他平台服務,主要是監聽埠實現解析http協議.js不需要拼串成XML,伺服器才要拼串,JS是運行在客戶端的,客戶端也不是通過SOAP與服務端進行通訊的,而是根據需要調用的服務的WSDL,提供對應參數,客戶端與服務端的通訊是用http協議的,而通訊方式根據是GET還是POST把相關參數放到HTTP頭或者體中.而web service之間的通訊才可能用得到SOAP.
3、PHP調用web service是非常簡單的,貌似有個函數通過SOAP調用.C++編寫的web service肯定有WSDL,可以根據WSDL描述的埠參數,來調用.
❺ C#使用webservice把文件上傳到伺服器
C#使用webservice把文件上傳到伺服器的代碼如下(這里以C:\.jpg這個文件上傳為例):
WebService部分:
///<summary>
///保存文件到遠程伺服器
///</summary>
///<paramname="FileByteArray">待轉換位元組數組</param>
///<paramname="FileLength">位元組長度</param>
///<paramname="SaveToUrl">保存路徑</param>
///<returns>返回是否執行成功</returns>
[WebMethod(Description="保存文件到遠程伺服器.")]
publicboolSaveFile(byte[]FileByteArray,intFileLength,stringSaveToUrl)
{
try
{
FileStreamfs=newFileStream(SaveToUrl,FileMode.OpenOrCreate,FileAccess.Write);
fs.Write(FileByteArray,0,FileLength);
fs.Close();
}
catch{
returnfalse;
}
returntrue;
}
上傳文件調用部分:
protectedvoidButton1_Click(objectsender,EventArgse)
{
MangerPhoto.Servicemp=newMangerPhoto.Service();
Response.Write(mp.SaveFile(getByte(),FileUpload1.PostedFile.ContentLength,"C:\.jpg"));
}privatebyte[]getByte(){//獲得轉化後的位元組數組
//得到用戶要上傳的文件名
stringstrFilePathName=FileUpload1.PostedFile.FileName;
stringstrFileName=Path.GetFileName(strFilePathName);
intFileLength=FileUpload1.PostedFile.ContentLength;
//上傳文件
Byte[]FileByteArray=newByte[FileLength];//圖象文件臨時儲存Byte數組
StreamStreamObject=FileUpload1.PostedFile.InputStream;//建立數據流對像
//讀取圖象文件數據,FileByteArray為數據儲存體,0為數據指針位置、FileLnegth為數據長度
StreamObject.Read(FileByteArray,0,FileLength);
returnFileByteArray;
}
❻ JAVA調用C語言發布的webservice介面
Java調用WebService可以直接使用Apache提供的axis.jar自己編寫代碼,或者利用Eclipse自動生成WebService Client代碼,利用其中的Proxy類進行調用。理論上是一樣的,只不過用Eclipse自動生成代碼省事些。
1、編寫代碼方式:
packagecom.yun.test;
importjava.rmi.RemoteException;
importorg.apache.axis.client.Call;
importorg.apache.axis.client.Service;
importorg.apache.axis.message.PrefixedQName;
importorg.apache.axis.message.SOAPHeaderElement;
importcom.cezanne.golden.user.Exception;
importcom.cezanne.golden.user.UserManagerServiceProxy;
importjavax.xml.namespace.QName;
importjava.net.MalformedURLException;
importjavax.xml.rpc.ServiceException;
importjavax.xml.soap.Name;
importjavax.xml.soap.SOAPException;
publicclasstestWebService{
publicstaticStringgetResult()throwsServiceException,MalformedURLException,RemoteException,SOAPException
{
//標識WebService的具體路徑
Stringendpoint="WebService服務地址";
//創建Service實例
Serviceservice=newService();
//通過Service實例創建Call的實例
Callcall=(Call)service.createCall();
//將WebService的服務路徑加入到call實例之中.
call.setTargetEndpointAddress(newjava.net.URL(endpoint));//為Call設置服務的位置
//由於需要認證,故需要設置調用的SOAP頭信息。
NameheaderName=newPrefixedQName(newQName("發布的wsdl里的targetNamespace里的url","string_itemName"));
org.apache.axis.message.SOAPHeaderElementheader=newSOAPHeaderElement(headerName);
header.addTextNode("blablabla");
call.addHeader(header);
//=newSOAPHeaderElement("發布的wsdl里的targetNamespace里的url","SoapHeader");
//soapHeaderElement.setNamespaceURI("發布的wsdl里的targetNamespace里的url");
//try
//{
//soapHeaderElement.addChildElement("string_itemName").setValue("blablabla");
//}
//catch(SOAPExceptione)
//{
//e.printStackTrace();
//}
//call.addHeader(soapHeaderElement);
//調用WebService的方法
org.apache.axis.description.OperationDescoper;
org.apache.axis.description.ParameterDescparam;
oper=neworg.apache.axis.description.OperationDesc();
oper.setName("opName");
param=neworg.apache.axis.description.ParameterDesc(newjavax.xml.namespace.QName("","arg0"),org.apache.axis.description.ParameterDesc.IN,newjavax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema","string"),java.lang.String.class,false,false);
param.setOmittable(true);
oper.addParameter(param);
param=neworg.apache.axis.description.ParameterDesc(newjavax.xml.namespace.QName("","arg1"),org.apache.axis.description.ParameterDesc.IN,newjavax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema","string"),java.lang.String.class,false,false);
param.setOmittable(true);
oper.addParameter(param);
param=neworg.apache.axis.description.ParameterDesc(newjavax.xml.namespace.QName("","arg2"),org.apache.axis.description.ParameterDesc.IN,newjavax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema","string"),java.lang.String.class,false,false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(newjavax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema","string"));
oper.setReturnClass(java.lang.String.class);
oper.setReturnQName(newjavax.xml.namespace.QName("","return"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(neworg.apache.axis.description.FaultDesc(
newjavax.xml.namespace.QName("發布的wsdl里的targetNamespace里的url","Exception"),
"Exception",
newjavax.xml.namespace.QName("發布的wsdl里的targetNamespace里的url","Exception"),
true
));
call.setOperation(oper);
call.setOperationName(newjavax.xml.namespace.QName("發布的wsdl里的targetNamespace里的url","opName"));
//調用WebService,傳入參數
Stringres=(String)call.invoke(newObject[]("arg0","arg1"));
System.out.println("===============");
returnres;
}
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
try{
System.out.println(getResult());
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(RemoteExceptione){
e.printStackTrace();
}catch(ServiceExceptione){
e.printStackTrace();
}catch(SOAPExceptione){
e.printStackTrace();
}
}
}
2、利用Eclipse自動生成WebService client代碼就容易多了:
首先,new project,選擇other,在輸入框中輸入Web Service Client,選中搜索後的結果,點擊Next,在Service definition中輸入 WebService的發布地址,點擊Finish
這樣,WebService Client代碼已經生成好了。
接下來寫一個Test類,在main函數中輸入如下代碼:
Stringendpoint="伺服器的WebService的地址";
YourWebServiceNameProxyumsp=newYourWebServiceNameProxy(endpoint);
try{
StringresultStr=umsp.opMethod("arg0","arg1");
System.out.println(resultStr);
}catch(Exceptione){
System.out.println("異常");
e.printStackTrace();
}catch(RemoteExceptione){
System.out.println("RemoteException異常");
e.printStackTrace();
}
❼ 如何在C#中webservice調用方法總結
一、WebService在cs後台程序中的調用
A、通過命名空間和類名直接調用
示例:
WebService ws = new WebService();
string s = ws.HelloWorld();
B、通過添加WEB引用的方式調用,首先添加WEB引用,通過URL指向WEBSERVICE,
指定WEB引用名,假設為KK;
示例:
kk.WebService n = new kk.WebService();
string ss=n.HelloWorld();
二、WebService在前台頁面的JS 調用方法
1、首先通過下面的方法把Webservice在前台引用進來
<asp:ScriptManager runat="server">
<Services>
<asp:ServiceReference Path="WebService.asmx" InlineScript="True" />
</Services>
</asp:ScriptManager>
2、然後就可以通過JS程序進行調用,示例如下:
<script type="text/jscript">
function a()
{
WebService.HelloWorld(onresult);
}
//這里的onresult是回調函數
function onresult(result)
{
alert(result);
}
function b()
{
WebService.add(1,2,onreturn)
}
function onreturn(result)
{
alert(result);
}
//下面的'context'是上下文,可以通過回到函數通過重載的方式獲得;
function c()
{
WebService.div(1,1,onresultC,onerror,'context');
}
function onresultC(res,c)
{
alert(res);
alert(c);
}
//onerror是獲得異常信息的回調函數,下面給出了獲得異常信息的方法
function onerror(error)
{
var a="";
a=String.format("獲取伺服器端異常的具體類型:{0}\t\n獲取詳細的異常描述信息:{1}\t\n獲取造成異常的:{2}\t\n獲取伺服器端異常的堆棧
跟蹤信息:{3}\t\n獲取一個布爾值,表示異常是否是由於網路連接超時造成的{4}",
error.get_exceptionType(),
error.get_message(),
error.get_statusCode(),
error.get_stackTrace(),
error.get_timedOut())
alert(a);
}
a();
b();
c();
</script>
----自寫小例子---
web Service---:
[WebMethod]
public string HelloWorld() {
return "Hello World,wwg";
}
[WebMethod]
public int AddWwg(int a,int b)
{
return a + b;
}
exe---
using CallWebService.localhost; //因為自己沒有定義命名空間
namespace CallWebService
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Service serviceWwg = new Service();
int i1 = Int32.Parse(txt1.Text.ToString());
int i2 = Int32.Parse(txt2.Text.ToString());
int iResult = serviceWwg.AddWwg(i1, i2);
lb1.Text = iResult.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
CallWebService.localhost.Service serviceWwg = new CallWebService.localhost.Service();
string strResult = serviceWwg.HelloWorld();
lb1.Text = strResult.ToString();
}
}
}
❽ 如何編寫webservice c
採用的工具VS2010生成工程
1. 生成webservice工程:建 ASP.NET 空WEB 應用程序。
2. 在建好的ASP.NET 空WEB應用程序中新建項「web 服務」。
完成上述內容工程結構如下圖
2. 然後再重新生成一下測試項目,最後在測試項目中定義一個測試方法並調用webservice中的方法。代碼如下
3.單步調試一下若運行結果和預料一樣則成功了。
❾ 最簡單的webservice如何寫
在開始下面這個例子之前,你的系統需要:
1、WIN2000 + IIS;
2、VS.Net;
3、SQL Server(我這里用的是SQL資料庫);
這個Web Service的例子用的是MS大吹的C#寫的,如果你喜歡VB,那麼用VB也是一樣的哦,只不過語法上一些小的差別而已,道理都是一樣的,不過即然MS都鼓吹C#,如果你能夠用C#寫還是用這為好哦。
下面是寫的步驟:
一、打開VS。NET的集成開發環境,FILE菜單上選擇New,新建一個C#的ASP.NET Web Service工程,工程名為WebServiceDemo(完整的是http://localhost/WebServiceDemo)。這是VS就在你的Web系統目錄下生成了相應的文件,我的服務目錄是默認的c:\Inetpub\wwwroot,生成的文件就在c:\Inetpub\wwwroot\webserviceDemo下,就不多說了。
二、打開與生成工程對應的C#源文件,這里是Service1.asmx.cs,VS.Net集成環境已經為你生成了相應的代碼如下:
// =============================================================================
// 文件: Service1.asmx.cs
// 描述: 架構一個Web Service來對資料庫進行互訪
//
//
// ============================================================================
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
// 系統生成了與工程名相同的命名空間
namespace WebServiceDemo
{
/// <summary>
/// Summary description for Service1.
/// </summary>
// 所有的WEB服務都是派生於System.Web.Services.WebService的。
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeComponent();
}
}
}
裡面我添加了文件說明和相應的注釋,接下來就是在裡面編寫相應的服務代碼了。這里我想先把對資料庫的操作封裝在同一命名空間的單獨的一個類里,下面編寫WEB方法時只用接調用這個類中的相應方法就可以了。下面是我寫的這個類的代碼:
// -------------------------------------------------------------------------
// 構建一個新類,用於對數據的訪問
// -------------------------------------------------------------------------
public class DataAccess
{
// 連接字元串成員變數
private string m_szConn = "";
private SqlConnection m_sqlConn;
private SqlDataAdapter m_sqlDa;
// 構造函數
public DataAccess(string szConnectionString)
{
m_szConn = szConnectionString;
}
// 返回一個記錄集
public DataSet GetDataset(string szCommandText)
{
DataSet sqlDs;
try
{
m_sqlConn = new SqlConnection(m_szConn);
m_sqlConn.Open();
m_sqlDa = new SqlDataAdapter(szCommandText,m_sqlConn);
sqlDs = new DataSet();
m_sqlDa.Fill(sqlDs);
m_sqlConn.Close();
return sqlDs;
}
catch
{
return null;
}
}
// 重載上述方法
public DataSet GetDataset(string szCommandText, string szTableName)
{
DataSet sqlDs;
try
{
m_sqlConn = new SqlConnection(m_szConn);
m_sqlConn.Open();
m_sqlDa = new SqlDataAdapter(szCommandText,m_sqlConn);
sqlDs = new DataSet();
m_sqlDa.Fill(sqlDs,szTableName);
m_sqlConn.Close();
return sqlDs;
}
catch
{
return null;
}
}
}
這些就不多說了,與創建一般的C#類是一樣的。類中有三個函數,其中一個為構造函數,調用時傳入連接字元串。另外兩個函數都是一樣的作用,返回用戶需要的記錄集,只不是調用時傳的參數不一樣,實質都是一樣的。
下面就是在Service1類中添加真正用於WEB調用的代碼了,這部分才是給WEB應用程序調用的東西。在編寫這個類的代碼之前,應該先申請一個服務命令空間,設置相應的屬性,這一句可萬萬不能少哦,呵呵~,它告訴了WEB服務存放的路徑等相關的信息。如下:
// 聲明一個服務空間
[WebService(
Namespace = "http://localhost/WebServiceDemo/", //其實這個才是最重要的啦~,其它的都可以不要哦
Name = "Web Service Demo",
Description = "Web Service Demo"
)]
下面是Service1的代碼:
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeComponent();
}
#region Component Designer generated code
//Required by the Web Services Designer
private IContainer components = null;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
// 連接字元串常量
const string szConn = "server=(local)\\taoyi;uid=sa;pwd=;"
+ "initial catalog=mydata;data source=taoyi";
[WebMethod]
public String About()
{
return "這是一個C#編寫的Web Service演示程序!";
}
// 返回其中一個WebServiceDemo表
[WebMethod]
public DataSet GetServiceDemoTable()
{
DataSet sqlDs = new DataSet();
DataAccess dataAcc = new DataAccess(szConn);
string szSql = "Select * From WebServiceDemo";
sqlDs = dataAcc.GetDataset(szSql,"Demo");
return sqlDs;
}
// 返回由用戶指定的查詢
[WebMethod]
public DataSet GetByUser(string szCommandText)
{
DataSet sqlDs = new DataSet();
DataAccess dataAcc = new DataAccess(szConn);
sqlDs = dataAcc.GetDataset(szCommandText);
return sqlDs;
}
}
是不是很簡單哦,就只這么點,呵呵~,不過也可以說明問題的了。這個類中聲明了三個WEB方法,有沒有發覺呢?每個方法的前面都加了[WebMethod],表示該方法為WEB方法。呵呵,如果你想要你寫的函數可以讓WEB應用程序調用的話,這個可不能少的啦~,不然WEB應用程序就無法調用的。
到此一個WEB服務就完成了,點擊運行看看,如果沒什麼錯的話,就會出現如下的WEB頁面服務描述:
Service1
The following operations are supported. For a formal definition, please review the Service Description.
* GetByUser
* GetServiceDemoTable
* About
.....(下面還有很多)
其中代星號的就是先前在函數前加了[WebMethod]的函數。在出現在頁面中你可以單擊相應的函數,然後就會跳到調用頁面,你可以在相應的文本框中(如果函數有參數的話)輸入相應的參數,點而調用按鈕,那麼就可以看到函數返回的結果了(前提是函數調用無錯的話),不過全是XML格式的文本。比如我的GetServiceDemoTable函數調用的結果如下:
<?xml version="1.0" encoding="utf-8" ?>
- <DataSet xmlns="http://tempuri.org/">
- <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
- <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:Locale="zh-CN">
- <xs:complexType>
- <xs:choice maxOccurs="unbounded">
- <xs:element name="Demo">
- <xs:complexType>
- <xs:sequence>
<xs:element name="ID" type="xs:int" minOccurs="0" />
<xs:element name="szUser" type="xs:string" minOccurs="0" />
<xs:element name="szSex" type="xs:string" minOccurs="0" />
<xs:element name="szAddr" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
- <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
- <NewDataSet xmlns="">
- <Demo diffgr:id="Demo1" msdata:rowOrder="0">
<ID>1</ID>
<szUser>taoyi</szUser>
<szSex>男</szSex>
<szAddr>四川瀘州</szAddr>
</Demo>
- <Demo diffgr:id="Demo2" msdata:rowOrder="1">
<ID>2</ID>
<szUser>xiner</szUser>
<szSex>女</szSex>
<szAddr>四川宜賓</szAddr>
</Demo>
</NewDataSet>
</diffgr:diffgram>
</DataSet>
到此為至,Web Service程序就已經算是完成了。
下面要做的是寫一個WEB應用程序來測試我寫的這個Web Service了,看看能不能達到想要的結果。建立Web應用程序的步驟如下:
一、新建一個ASP.Net Web Application工程,與創建Web Service的第一步一樣,只是工程類型不一樣罷了。我這里工程名為WebServiceDemoTest,完整的為http://localhost/WebServiceDemoTest,系統就在相應的目錄(c:\Inetpub\wwwroot\WebserviceDemoTest)下生成了所需文件。
二、在設計視圖下打開WebForm1.aspx文件,在裡面放置一個panel容器,為了達到測試的目的,我們需要三個服務端按鈕和一個服務端文本框,分別調用我們在Web Service中寫的三個函數,另外,為了展示調用方法所得達的數據,還需要一個服務端標簽控制項和一個DataGrid控制項。頁面的布置就隨便你了,想怎麼放置就怎麼放置,只要能達到演示的目的就行。
三、引用先前寫的Web Service程序,菜單步驟如下project->add web reference...,然後輸入我們Web Service的路徑,這里是http://localhost/WebServiceDemo/Service1.asmx,點擊添加就OK了。這時你將在類視圖中看到localhost命名空間了。
四、編寫測試代碼。
為了便於後面少寫些代碼,如(xxxx.xxxx.xx xx = new xxxx.xxx.xx()這種),那麼首先你得引用localhost命名空間的service1類,以後直接寫xxxx xx = new xxxx()就可以了。
下面是幾個按鈕的代碼:
// 測試GetServiceDemoTable()
private void Button2_Click(object sender, System.EventArgs e)
{
DataSet ds = new DataSet();
Service1 oService = new localhost.Service1();
// 返回記錄集
ds = oService.GetServiceDemoTable();
if (ds != null)
{
// 顯示記錄集的記錄
DataGrid1.DataSource = ds.Tables["Demo"];
DataGrid1.DataBind();
}
else
{
this.Response.Write("載入數據錯誤!");
}
}
// 測試GetByUser()
private void Button1_Click(object sender, System.EventArgs e)
{
DataSet ds = new DataSet();
Service1 oService = new localhost.Service1();
String szCommand = TextBox1.Text;
ds = oService.GetByUser(szCommand);
if (ds != null)
{
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
else
Response.Write("錯誤!有可能是SQL命令有問題!");
}
// 測試About()
private void Button3_Click(object sender, System.EventArgs e)
{
Service1 oService = new localhost.Service1();
Label1.Text = oService.About();
}
OK,最後就是運行了,如果一切OK,點擊第一個按鈕得到的將是在一個包函用戶執行的SQL命令的表結果。第二個按鈕得到的就是上面運行Web Service時的GetServiceDemoTable得到的XML描述,即
ID szUser szSex szAddr
1 taoyi 男 四川瀘州
2 xiner 女 四川宜賓
點擊第三個按鈕,則在Label1中顯示"這是一個C#編寫的Web Service演示程序!」的字元串
❿ c#中webservice未能找到文件「C:\WINDOWS\system32\user.xml
應該是程序本身的問題,用vs打開源代碼,在webservice項目中查找user.xml,打上斷點,調試,注意調試webservice要用F11才能進去。如果你的代碼中不存在user.xml的話,可能是你使用的組件在調用該user.xml,如果該組件是你的同事做的,你可能就只有問他們了。