SharePoint提供的WebServices中没有直接取到附件内容的,都是提供了附件的地址,还需要用WebClient带上身份取,那样可能会因为iis的一些配置被屏蔽掉。
先用ASP.NET Web 服务模板新建一个网站,将App_Code下的文件删除,然后再添加一个类库项目,cs文件代码如下:
1using System;
2using System.Web;
3using System.Web.Services;
4using System.Web.Services.Protocols;
5using Microsoft.SharePoint;
6using Microsoft.SharePoint.Utilities;
7using System.IO;
8[WebService(Namespace = "http://tempuri.org/")]
9[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
10public class Service : System.Web.Services.WebService
11{
12 public Service()
13 { }
14
15 [WebMethod]
16 public object[] GetAttachments(string listName, int itemID)
17 {
18 SPWeb myWeb = SPContext.Current.Web;
19 SPList myList = myWeb.Lists[listName];
20 SPListItem myItem = myList.GetItemById(itemID);
21 int attCount = myItem.Attachments.Count;
22 string[] myAttUrl = myItem.Attachments.UrlPrefix.Split('/');
23 string attachUrl = string.Empty;
24 for (int i = 3; i < myAttUrl.Length; i++)
25 {
26 attachUrl += "/" + myAttUrl[i];
27 }
28
29 object[] attachmentsObject = new object[attCount * 2];
30 for (int i = 0; i < attCount; i++)
31 {
32 attachmentsObject[i] = myItem.Attachments[i];
33 SPFile myFile = myWeb.GetFile(attachUrl + myItem.Attachments[i]);
34 attachmentsObject[attCount + i] = myFile.OpenBinary();
35 }
36 return attachmentsObject;
37 }
38}
编译类库以后将dll文件拷贝到GAC中,将asmx文件内容改为<%@ WebService Language="C#" Class="Service, SPAttachments, Version=1.0.0.0, Culture=neutral, PublicKeyToken=890647b58f8f1295" %>
到这一步,WebServices应该可以在解决方案中调试运行了 。
使用VS .NET命令行工具生成disco 和 wsdl文件,命令如下:
Disco http://localhost:Port/Project_Name/Service1.asmx
端口 port是.NET调试自动分配的,然后到命令行工具目录下找到disco和wsdl文件
两个文件改成Attachmentsdisco.aspx和Attachmentswsdl.aspx复制到\12\ISAPI目录下,同时将Attachments.asmx页也复制到该目录,disco中代码可以直接复制该目录里其他类似的网页,aspx将头和 <wsdl:service name="Service">代码段改成类似的网页格式即可。然后在该目录下找到spdisco.aspx文件,在</discovery>前面添加如下两行:
<contractRef ref=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(spWeb.Url + "/_vti_bin/Attachments.asmx?wsdl"),Response.Output); %> docRef=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(spWeb.Url + "/_vti_bin/Attachments.asmx"),Response.Output); %> xmlns="http://schemas.xmlsoap.org/disco/scl/" />
<discoveryRef ref=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(spWeb.Url + "/_vti_bin/Attachments.asmx?disco"),Response.Output); %> xmlns="http://schemas.xmlsoap.org/disco/" />
再重启IIS即可调用。我遇到的问题是有时候修改类库中的方法再重新部署时不更新……还在研究中
源码