在Sitecore中, 虽然已经提供了一些webservice供开发者使用,但这些webservice都比较简单,另外缺少用户管理的webservice接口。所以有时需要自己开发一些接口供第三方系统调用。下面就介绍一下如何创建一个WCF服务完成新建用户的功能。
1. 在VS中新建一个WCF项目,添加以下DLL文件引用
- log4net.dll
- Lucene.Net.dll
- NUnit.Framework.dll
- Sitecore.Kernal.dll
- Sitecore.Logging.dll
- Sitecore.Nexus.dll
- System.Configuration.dll
2. 从已有的Sitecore website目录下的web.config 中 复制 以下代码到App.config的开头
<configSections>
<section name="sitecore" type="Sitecore.Configuration.ConfigReader, Sitecore.Kernel"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, Sitecore.Logging"/>
</configSections>
3. 从已有的Sitecore website目录下的web.config 中 复制 以下节点到App.config
中,其中如果需要调用security的api时,必须添加system.web节点配置,否则可以不用
- connectionStrings
- appSettings
- sitecore
- log4net
- system.web
4. 将App.config中的“/App_Config/” 全部替换为“.\App_Config\”
5. 将已有Sitecore website目录下的 App_Config 文件夹加入项目,并把下面的所有文件的“复制到输出目录”属性都改为“始终复制”
至此 环境配置已经完成,下面编写WCF代码
接口类ISitecoreService:
[ServiceContract]
public interface ISitecoreService
{
[OperationContract]
string CreateUser(string userName);
}
实现类 SitecoreService:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class SitecoreService : ISitecoreService
{
public string CreateUser(string userName)
{
using (new SecurityDisabler())
{
var domainUser = @"extranet\" + userName;
if (!User.Exists(domainUser))
{
//create
User user = User.Create(domainUser, "b");
return user.Name;
}
return "has existed";
}
}
}
测试运行:
大功到成!其他操作Sitecore Item的功能也可以类似开发。只要注意,由于是webservice,没有上下文,所以Sitecore.Context 不能使用,获取item需要用以下方法:
Sitecore.Configuration.Factory.GetDatabase("master").GetItem(id);