Sharepoint Foundation 2010 サイトのカスタム Web パーツからロードされた JavaScript から AJAX によって呼び出すことができる WCF をセットアップしたいと考えています。Javascript 側の処理を簡素化するために、呼び出し元に Json を返す Restful サービスを提供したいと考えています。
問題は、AJAX 呼び出しでサーバーを呼び出すと、SPContext.Current が null になることです。
svc ファイルで MultipleBaseAddressWebServiceHostFactory を使用して Web サービスを作成しています
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$"%>
<%@ServiceHost Language="C#" Debug="true"
Service="Driftportalen.LvService.SuggestService"
Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
%>
Web サービスのコントラクトは次のとおりです。
[ServiceContract(Namespace = "", ProtectionLevel= ProtectionLevel.None)]
public interface ISuggestServiceTest
{
[WebGet(UriTemplate = "/SuggestAddress/{streetprefix}/", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Dictionary<string, GenericAddress> SuggestAddress(string streetprefix);
}
Webサービスの実装は基本的に以下の通りです。
[Guid("BA6733B3-F98D-4AD8-837D-7673F8BC527F")]
[BasicHttpBindingServiceMetadataExchangeEndpoint]
[ServiceBehavior(IncludeExceptionDetailInFaults = true, AddressFilterMode = AddressFilterMode.Any)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class SuggestService : ISuggestServiceTest
{
private SPWeb currentWeb;
public SPWeb CurrentWeb
{
get
{
if (currentWeb == null)
{
var siteUrl = SPContext.Current.Web.Url;
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (var site = new SPSite(siteUrl))
using (var web = site.OpenWeb())
{
currentWeb = web;
}
});
}
return currentWeb;
}
}
public Dictionary<string, GenericAddress> SuggestAddress(string streetprefix)
{
LvService lvService = new LvService(CurrentWeb);
Dictionary<string, GenericAddress> suggestions = new Dictionary<string, GenericAddress>();
//SNIP
//Code that uses lvService to populate suggestions
return suggestions;
}
}
Web ブラウザーから Web サービスを呼び出すと、すべてが期待どおりに機能し、正しいデータが返されることを確認しました。
次のAjax呼び出しを使用します
$.ajax({
url: addressUrl + "/"+request.term,
dataType: 'json',
success: function (data) {
responseCallback(data);
$(this).removeClass("fetching");
}
});
Firebug を使用して、JavaScript から正しい URL が呼び出されることを確認し、サーバー側で正しいコードに実際に到達したことを確認しましたが、SPContext.Current は null です。
SharePoint サーバーは、ログインに Windows と Claims を使用します。これは、実際の WCF が SharePoint ソリューションとは異なるアカウントを使用して実行されることを意味しますが、vti_bin の下のフォルダーにデプロイするため、Sharepoint はそのコンテキストを WCF に提供する必要があります。AJAX呼び出しがSharepointをトリガーしてそのコンテキストを提供しないように思えます。ある意味では匿名です。
最初は、ブラウザから呼び出されたときにランダムに失敗するため、Web サービス自体が原因であると想定していましたが、Sharepoint Foundation 2010 へのアップグレードをインストールすることで、その問題を解決したと思います。
SharePoint サイトにサインインしたユーザーのコンテキストに Web サービスがアクセスできるようにする Javascript からの AJAX 呼び出しを受け入れる javascript/a Web サービスから AJAX 呼び出しを行うにはどうすればよいですか?