實(shí)現(xiàn)帶有用戶身份驗(yàn)證的文件傳輸Web Service(3) (轉(zhuǎn))
2024-07-21 02:21:30
供稿:網(wǎng)友
作者: 曹勇剛 www.aspcool.com 時(shí)間:2001-11-28 22:51:59 閱讀次數(shù):493
下面我們生成一個(gè)web service,起名叫fileserver,在fileserver.asmx中有如下代碼:
<%@ webservice language="c#" codebehind="fileserver.asmx.cs" class="useresdata.fileserver" %>
大家可以看到codebehind技術(shù)是如何被使用的。在visual studio.net中,自動(dòng)生成的代碼大量使用這樣的語(yǔ)句。它使得設(shè)計(jì)頁(yè)面和編寫(xiě)代碼被劃分開(kāi)了。
在fileserver.asmx.cs中,代碼如下:
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.diagnostics;
using system.web;
using system.web.services;
using system.io;
namespace useresdata
{
///
/// summary description for fileserver.
///
public class fileserver : system.web.services.webservice
{private string rootdir;
public fileserver()
{
//codegen: this call is required by the asp.net web services designer
initializecomponent();
rootdir=server.mappath("/caomo/提供傳輸?shù)奈募?quot;);
}
#region component designer generated code
///
/// required method for designer support - do not modify
/// the contents of this method with the code editor.
///
private void initializecomponent()
{
}
#endregion
///
/// clean up any resources being used.
///
protected override void dispose( bool disposing )
{
}
public authentication header; //定義用戶身份驗(yàn)證類(lèi)變量header。
[webmethod(description="need authentication!")]
[system.web.services.protocols.soapheader("header")]
//用戶身份驗(yàn)證的soap頭
public string getfile(string filepath)
{
if (header.validuser(header.username,header.password)) //用戶身份驗(yàn)證
{
filestream myfile=file.openread(rootdir+filepath);
binaryreader br=new binaryreader(myfile);
byte[] btbuf=new byte[myfile.length];
long i=0;
while (br.peekchar()>-1)
{
btbuf[i]=br.readbyte();
i++;
}
myfile.close();
return system.convert.tobase64string(btbuf);
}
else return null;//用戶身份驗(yàn)證failed
}
運(yùn)行它。將會(huì)得到如圖1所示頁(yè)面:
圖 1
大家應(yīng)該注意到名為getfile的服務(wù)是我給的代碼中的web method,下面的“need authentication!”是由webmethod定義中的description="need authentication!"給出的。