Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7517237
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T01:22:53+00:00 2026-05-30T01:22:53+00:00

I want to set up a WCF that can be called by AJAX from

  • 0

I want to set up a WCF that can be called by AJAX from a javascript loaded from a custom webpart on our Sharepoint Foundation 2010 site. To simplify the processing on the Javascript side I want to present a Restful service that give Json back to the caller.

Problem is that when I call the server with a AJAX call the SPContext.Current is null.

I am using MultipleBaseAddressWebServiceHostFactory the in svc file to create the webservice

<%@ 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"
     %>

The contract for the webservice is:

[ServiceContract(Namespace = "", ProtectionLevel= ProtectionLevel.None)]  
public interface ISuggestServiceTest
{
    [WebGet(UriTemplate = "/SuggestAddress/{streetprefix}/", ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    Dictionary<string, GenericAddress> SuggestAddress(string streetprefix);
}

Implementation of the webservice is basically as follows.

[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;
    }
}

I have verified that if I call the webservice from the webbrowser everything works as expected and that I get the right data back.

I use the following Ajax call

 $.ajax({
   url: addressUrl + "/"+request.term,
   dataType: 'json',
   success: function (data) {
      responseCallback(data);
     $(this).removeClass("fetching");
   }
});

Using Firebug I have verified that the correct URL is called from the javascript and I have verified on the server side that the right code is indeed reached, but SPContext.Current is null.

The Sharepoint server uses Windows and Claims for login. This means the actual WCF will be run using a different account than the Sharepoint solution, but since I deploy to a folder below vti_bin Sharepoint should provide its context to the WCF. It seems to me like the AJAX call won’t trigger Sharepoint to provide its context, in some sense it is anonymous.

At first I assumed the webservice itself was to blame since it would fail randomly when called from the browswer, but I think I sorted that issue out by installing a upgrade to Sharepoint Foundation 2010.

How can I make a AJAX call from the javascript/ a web service that accept AJAX calls from Javascript that allow the webservice to access the context of the user that has signed in to the Sharepoint site?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T01:22:54+00:00Added an answer on May 30, 2026 at 1:22 am

    I did figure out the solution of this problem so I want to share my findings in case anyone else stumbled into this kind of a problem.

    The basic problem is caused by fact that the Microsofts svc factories fail to add suiting access bindings for ajax calls. This mean the authenticiation magic of vti_bin folder will not happen. You get a running svc, but no Sharepoint context when you access it with ajax calls from your javascript even though ordinary access works fine.

    You can fix the issue by extending the Factory to replace the bindings with the correct ones

     <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$"%>  
     <%@ServiceHost Language="C#" Debug="true"
     Service="Driftportalen.LvService.SuggestService, $SharePoint.Project.AssemblyFullName$"
    Factory="Driftportalen.LvService.AjaxCompatibleRestServiceHostFactory,Driftportalen.LvService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ab8de4d18e388c1f"
             %>
    

    Implementation of the new Factory is as follows

    public class AjaxCompatibleRestServiceHostFactory : Microsoft.SharePoint.Client.Services.MultipleBaseAddressBasicHttpBindingServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            return new AjaxCompatibleRestServiceHost(serviceType, baseAddresses);
        }
    }
    

    And finally the actuall code to replace the bindings

    public class AjaxCompatibleRestServiceHost : Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHost
    {
    
        public AjaxCompatibleRestServiceHost(Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        {
        }
    
        protected override void OnOpening()
        {
            base.OnOpening();
    
            foreach (ServiceEndpoint endpoint in base.Description.Endpoints)
            {
                if (((endpoint.Binding != null) &&    (endpoint.Binding.CreateBindingElements().Find<WebMessageEncodingBindingElement>() != null)) && (endpoint.Behaviors.Find<WebScriptEnablingBehavior>() == null))
                {
                    // try remove any previous behaviours
                    while (endpoint.Behaviors.Count > 0)
                    {
                        endpoint.Behaviors.RemoveAt(0);
                    }
                    endpoint.Behaviors.Add(new WebHttpBehavior());
                }
    
            }
    
    
            ServiceDebugBehavior debug = this.Description.Behaviors.Find<ServiceDebugBehavior>();
            // if not found - add behavior with setting turned on 
            if (debug == null)
            {
                this.Description.Behaviors.Add(
                    new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
            }
            else
            {
                // make sure setting is turned ON    
                if (!debug.IncludeExceptionDetailInFaults)
                {
                    debug.IncludeExceptionDetailInFaults = true;
                }
            }
    
            ServiceMetadataBehavior metadata =this.Description.Behaviors.Find<ServiceMetadataBehavior>();
            // if not found - add behavior with setting turned on 
            if (metadata == null)
            {
                this.Description.Behaviors.Add(
                    new ServiceMetadataBehavior() { HttpGetEnabled = true });
            }
            else
            { 
                // make sure setting is turned ON    
                if (!metadata.HttpGetEnabled)
                {
                    metadata.HttpGetEnabled = true;
                }
            }
    
        }
    }
    

    Possibly you might want to use WebScriptEnablingBehavior instead of WebHttpBehavior if you want the result wrapped when you get them back.

    There are some additional things to consider. There is some indication on the net that lack of SP1 might also result in the lack of Sharepoint context, so verify that you have the latest service packs if you run into problems.

    Finally in case you are building a REST service it might be tempting to use UriTemplate to get the URL structure you desire. Unfortunately at the time of this writing UriTemplate is not supported by Microsoft in this scenario so investigate this issue before you base your design on the existence of UriTemplate.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm getting a List back from a WCF service and I want to set
I want to send a big XML string to a WCF SVC service from
I simply want to create a fairly basic REST service, so that I can
I have a custom class library that performs validation. I want to open up
I'm trying to set up a WCF service hosted in IIS that exposes an
The intent is to create a set of web services that people can reuse.
Can a single WCF Service endpoint be set up to authenticate against multiple Authentication
I have a RESTful WCF service that can return XML, JSON, or JSONP, depending
I have a WCF client that download content from the server. the service contract
I have a WCF service with Message Security Authentication . I want to set

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.