开发者

How do I consume a WCF Service from javascript in an ASP.NET WebForm?

开发者 https://www.devze.com 2023-02-10 10:31 出处:网络
I\'ve followed the instructions on MSDN : Exposing WCF Services to Client Script (http://msdn.microsoft.com/en-us/library/bb514961.aspx), however the example does not show how to actually consume the

I've followed the instructions on MSDN : Exposing WCF Services to Client Script (http://msdn.microsoft.com/en-us/library/bb514961.aspx), however the example does not show how to actually consume the service in javascript, which is where I am getting stuck.

I've created a very simple WCF service :

using System.ServiceModel; using System.Text; using System.ServiceModel.Activation;

namespace MyNamespace {

[ServiceContract(Namespace = "MyDomain.com")]
public interface IMyService
{
    [OperationContract]
    void DoWork();
}

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "McCormickProdService" in code, svc and config file together.
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
    public void DoWork()
    {
    }
}

}

I've also updated by web.config :

  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="default"/>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webScriptEnablingBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="MyNamespace.MyService"
         behaviorConfiguration="">
        <endpoint address="" binding="webHttpBinding"
          bindingConfiguration="default"
          contract="MyNamespace.IMyService"
          behaviorConfiguration="webScriptEnablingBehavior"/>
      </service>
    </services>
  </system.serviceModel>

And here is the code that I have cobbled together in ASP.NET / javascript :

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="false" EnableCdn="true" AjaxFrameworkMode="Explicit">
    <Scripts>
        <asp:ScriptReference Path="http://ajax.aspnetcdn.com/ajax/act/40412/start.js" />
    </Scripts>
    <Services>
        <asp:ServiceReference Path="~/Services/MyService.svc"/>
    </Services>
</asp:ScriptManager>
<asp:ContentPlaceHolder ID="endbody" runat="server" />

<script type="text/javascript">

    Sys.loader.defineScripts(null, [{ name: "jQueryUI", releaseUrl: "http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.min.js", dependencies: ["jQuery"], isLoaded: !!(window.jQuery && jQuery.ui)}]);
    Sys.loader.defineScripts(null, [{ name: "jQueryUIdatepickerfr", releaseUrl: "http://jquery-ui.googlecode.com/svn/trunk/ui/i18n/jquery.ui.datepicker-fr.js", dependencies: ["jQueryUI"], isLoaded: !!(window.jQuery && jQuery.ui)}]);

    Sys.require([
        Sys.scripts.ApplicationServices,
        Sys.scripts.Templates,
        Sys.scripts.DataContext,
        Sys.scripts.WebServices,
        Sys.scripts.jQuery,
        Sys.scripts.jQueryUI,
        Sys.scripts.jQueryUIdatepickerfr], function () {

            MyDomain.com.IMyService.DoWork(function () { alert('success') }, function () { alert('failure') }, null);
        });  

</script>

When I load my page, I am receiving the following errors :

Error: 'Sys.Net.WebServiceProxy' is null or not an object Error: Object doe开发者_运维技巧sn't support this property or method

Remarks :

  • I'm loading a couple of other scripts, such as jQuery and jQuery UI (including the French localization, which I could only find on Google for the time being).
  • I can't figure out if I absolutely have to use the Sys.require method, or if I could just reference the needed scripts directly using like we used to do in the olden days.
  • I placed the script manager and script elements at the bottom of my page, outside the form element but inside the body element, is this the right place, or should it all be in the head?
  • I set the EnableCDN parameter to true, thus I'm using the Microsoft content distribution network, although I'd really rather host these scripts myself. This is an internal project, which may have a long lifespan with little intervention, so I'd prefer not to have the rug pulled out from under my feet when Microsoft decides to upgrade their scripts and break compatibility. However, I can't actually figure out how to download these scripts, or if I even need to (perhaps they are bundled inside some resource file somewhere on my disk). Although I can find some of the scripts here: http://www.asp.net/ajaxlibrary/CDNAjax4.ashx, there are certain scripts that I can't find, such as MicrosoftAjaxTemplates.js (I'm not using Templates just yet, but I'd like to give it a bash later).
  • Do I need to reference the start.js script directly? I understand that this is the script that allows the Sys.require method to work, which then brings in the remainder of the scripts.
  • I have referenced System.scripts.WebServices directly; do I need to do this, or is this referenced automagically when I have a service reference?
  • Perhaps I'm chasing my tail for nothing and I don't need to use Sys.require at all ?!

Hope someone brilliant out there can give a dog a bone, because I'm lost!

Thanks,

Patrick


Figured out a bunch of things, perhaps this will be useful to others:

  • Sys.require is not needed. Simply adding brings in all the nice ASP.NET AJAX goodies. The actual .js files are wrapped up somewhere inside a binary file, thus they don't need to be downloaded to be able to run locally.
  • Once I ripped the Sys.require calls, my code started working.
  • The page load event is : Sys.Application.add_load(function() { code here... });
  • To simplify your code doright-click -> view markup on the Service1.svc file, and change the service host to use the web script service host factory, as follows : <%@ ServiceHost Service="MyService" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>
  • There is no need for the ServiceBehaviour or AspNetCompatibilityRequirements attributes.
  • All that is required in the web.config is:

    <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" /> (or true for testing)
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    

  • Voilà!

0

精彩评论

暂无评论...
验证码 换一张
取 消