Adding web service bindings into SharePoint web.co

2020-06-07 05:13发布

问题:

I have a SharePoint web part which uses a WCF service. To be able to consume the web service in my web part, I need to modify the SharePoint web.config to include bindings and end points.

What's the best way to do this?

回答1:

This was very useful but it missed a bit. Whereas the code can be deployed, it can't be retracted because a name wasn't assigned.

Use:

modification.Name = "bindings";

Also, having said that this is bindings, you (probably) can't still can't apply the settings if there are already settings there for:

serviceHostingEnvironment aspNetCompatibilityEnabled="true"  

... inside the system.serviceModel

I've used the technique to insert the bindings and then the client end point gets inserted separately as this can change according to installation and in my case is set via a sharepoint list entry.



回答2:

To be able to do this, I put my web service configuration into a text file as a template. The text file (BindingTemplate.txt) content is as the following:

<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_AuthenticationInterface" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="http://{0}/MyWebService/AuthenticationService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_AuthenticationInterface" contract="AuthenticationService.AuthenticationInterface" name="BasicHttpBinding_AuthenticationInterface" />
</client>

I used the C# following code to modify the web.config:

string content;
string WebServiceServer = "example.com"; // <=== your host-name here
using (TextReader tr = File.OpenText(bindingFilePath))
{
    content = String.Format(tr.ReadToEnd(), WebServiceServer);
}

SPWebConfigModification modification = new SPWebConfigModification("system.serviceModel", "configuration");
modification.Value = content;
modification.Sequence = 0;
modification.Type =SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
modification.Owner = OWNER_CONSTANT;

webApp.WebConfigModifications.Add(modification);

I spent some time figuring it out. Hope this will help someone.