为SharePoint 2010创建自定义WCF服务

主要有两种类型的WCF应用程序可供我们与SharePoint 2010列表进行交互:

1、标准的WCF服务应用程序,部署在IIS和SharePoint 2010根目录。

2、全新的基于REST的服务,原生支持通过ISAPI文件夹进行访问。

在本文中,我们将创建一个标准的WCF服务,并在随后的客户端应用程序中消费它。

为了可以利用WCF,我们将完成这些主要的步骤:

1、创建服务代码

2、发布并部署服务代码

3、在客户端应用程序中消费该服务代码

创建服务代码

1、在Visual Studio 2010中创建一个标准的WCF服务应用程序。必须选择目标.NET Frameword 3.5。

2、添加Microsoft.SharePoint.dll到该项目。

3、创建一个契约(Contract)-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

using System.Text;
namespace UpdateSPList
{
[ServiceContract]
public interface IService1
{
[OperationContract]
void updateProduct(string SPSite, string prodName,string prodSKU, string prodPrice);
}}

注意:在该服务中,只暴露了一个方法供应用程序调用,接收4个参数:站点的URL( 比如,http://Spsite),产品名称,产品SKU,和产品价格(Products列表中的三个字段)。

4、服务代码- 这里将在名为“ListProducts”的列表中创建一个新的列表项。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.SharePoint;
namespace UpdateSPList
{
public class Service1 : IService1
{
public void updateProduct(string SPSite, string prodName,string prodSKU, string prodPrice)
{
string strDashListRoot = SPSite;
using (SPSite site = new SPSite(strDashListRoot))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists[“ListProducts”];
SPListItem Item = list.Items.Add();
Item[“Title”] = prodName;
Item[“Product_SKU”] = prodSKU;
Item[“Price”] = prodPrice;
Item.Update();
web.AllowUnsafeUpdates = false;
}
}}}}

5、部署 - 创建好一个WCF服务应用程序后,你可以将该服务代码部署到IIS。首先需要在服务器的文件系统中创建一个文件夹,然后将你的代码发布到该文件夹,最后将该文件夹映射为IIS网站的一个虚拟目录。

你可能还需要把web.config文件(一个XML文件包含了有关你的服务的配置信息)中的一些信息添加到SharePoint 的web.config(也是一个XML的配置文件,但是位于c:\Inetput\wwwroot\wws\VirtualDirectories\<Site Name>)中,以确保你的WCF服务在SharePoint服务器上运行良好。在IIS中创建好网站后,你可以通过在IIS中右击并选择在浏览器中查看,来测试我们的服务。

下面的文章中将介绍如何子客户端应用程序中使用该WCFf服务。

 

参考资料

Create custom wcf service for sharepoint 2010

posted @ 2010-10-16 17:28  Sunmoonfire  阅读(204)  评论(0)    收藏  举报