SharePoint Web Service系列:编写自定义SharePoint Web Services之二

  下面,我们要将我们的Web服务添加到WSSWeb服务列表中,这样就可以在VS.NET中添加该Web服务的引用了。

1、打开spdisco.aspx文件,该文件位于Local_Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\60\ISAPI目录。

2、在文件末尾的discovery元素中添加下面的内容,保存。

<contractRef ref=<% SPEncode.WriteHtmlEncodeWithQuote(Response, spWeb.Url + "/_vti_bin/Service1.asmx?wsdl", '"'); %> docRef=<% SPEncode.WriteHtmlEncodeWithQuote(Response, spWeb.Url + "/_vti_bin/Service1.asmx", '"'); %> xmlns="http://schemas.xmlsoap.org/disco/scl/" />
<soap address=<% SPEncode.WriteHtmlEncodeWithQuote(Response, spWeb.Url + "/_vti_bin/Service1.asmx", '"'); %>
 xmlns:q1="http://schemas.microsoft.com/sharepoint/soap/directory/" binding="q1:Service1Soap" xmlns="http://schemas.xmlsoap.org/disco/soap/" />

注意:soap元素的binding属性中在 "Soap"之前的文字(该例中的binding="q1:Service1Soap")指定了定义Web service时使用的类名。

 至此,我们的自定义Web service就部署完成了。我们可以像使用默认的Web service一样来调用我们的自定义Web service了。

创建文档上载Web服务

我们可以使用上面的方法来建立文档上载Web服务来上载文档到一个WSS的共享文档文档库。该服务利用服务虚拟化来获取站点上下文,然后上载文档到指定的文档库。

创建一个Web service项目,名为UploadSvc。添加一个新的Web service类命名为UploadFile

添加对Windows SharePoint Services (Microsoft.Sharepoint.dll)的引用。

UploadFile类中添加下面的Web方法:

[WebMethod]
public string UploadDocument(string fileName, byte[] fileContents, string pathFolder)
{
    
if ( fileContents == null)
    {
        
return "Null Attachment";
    }
   
try
   {
        SPWeb site 
= SPControl.GetContextWeb(Context);
        SPFolder folder 
= site.GetFolder(pathFolder);
        
string fileUrl = fileName;
        SPFile file 
= folder.Files.Add(fileUrl, fileContents);
        
return file.TimeCreated.ToLongDateString()+ "::" + file.Title;
   }
   
catch (System.Exception ee)
    {
        
return ee.Message + "::" + ee.Source;
    }
}

添加下面的命名空间引用:

using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

编译该Web service项目。

创建并修改.disco.wsdl并修改spdisco.aspx, 需要将上面的Service1 替换成UploadFile。分别保存为UploadFiledisco.aspxUploadFilewsdl.aspx

拷贝这些文件到_vti_bin, 拷贝对应得.dll _vti_bin/bin

调用上载文件服务的例子

新建一个WinForm应用程序,添加Web引用,并将该引用命名为WSSServer

添加一个button和两个textbox到默认的窗体,一个textbox用来输入上载文件的路径,另一个用来指定要上载到哪个文档库。如http://Server_Name/sites/Target_Site/Document_Library

添加下面的代码到buttonClick事件中。

WSSServer.UploadFile svcDocLib = new WSSServer.UploadFile();
svcDocLib.Credentials 
= CredentialCache.DefaultCredentials;

string strPath = textBox1.Text;
string strFile = strPath.Substring(strPath.LastIndexOf("\\"+ 1);
string strDestination = textBox2.Text;
 
FileStream fStream 
= new FileStream(strPath, System.IO.FileMode.Open);
byte[] binFile = new byte[(int)fStream.Length];
fStream.Read(binFile, 
0, (int)fStream.Length);
fStream.Close();
 
string str = svcDocLib.UploadDocument(strFile, binFile, strDestination);
MessageBox.Show(str);

添加命名空间引用:

using System.Net;
using System.IO;

编译运行。
(结束)

原文地址:https://www.cnblogs.com/Sunmoonfire/p/544735.html