2

I have followed below link to create a ajax enabled service in my project https://msdn.microsoft.com/en-us/library/bb924552(v=vs.110).aspx

My Asp.Net web forms project has multiple forms in different folders. The admin folder contains form for administration. I created wcf service from the admin folder and the code is as follows

namespace App.secure.Admin
{
    [ServiceContract(Namespace = "App.secure.Admin")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Admin
    {
        [OperationContract]
        public string updateComp(string city, string desc )
        {

In my webform, I could not add seperate ScriptManager, as I already had ToolkitScriptManager in the form.

I have added the service reference as follows

 <ajx:ToolkitScriptManager runat="server" ID="sm1">
        <Services>
            <asp:ServiceReference Path="Admin.svc" />
        </Services>
    </ajx:ToolkitScriptManager>

when I am trying to call the wcf service call, it is not able to instantiate the class in wcf service

 function UpdateStudent(e) {
       city = $("#spnCity").text();
       desc = $("#txtDescEd").val();
       var service = new App.secure.Admin.Admin();
       service.updateComp(city,  desc);
   }

When I run the application

Unhandled exception in http://localhost/secure/Admin/Add.aspx
0x800a1391 - JavaScript runtime error: 'App' is undefined

I have tried moving the WCf service to the root folder and tried calling it, but it was giving the same error.

The add.aspx.cs file, I am using

namespace App.secure
{
    public partial class Add : System.Web.UI.Page

The web.config:

<system.serviceModel>
        <behaviors>
            <endpointBehaviors>
                <behavior name="App.AdminSvcAspNetAjaxBehavior">
                    <enableWebScript />
                </behavior>
                <behavior name="App.secure.Admin.AdminAspNetAjaxBehavior">
                    <enableWebScript />
                </behavior>
            </endpointBehaviors>
        </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> 
        <services>
            <service name="App.AdminSvc">
                <endpoint address="" behaviorConfiguration="App.AdminSvcAspNetAjaxBehavior" binding="webHttpBinding" contract="App.AdminSvc" />
            </service>
            <service name="App.secure.Admin.Admin">
                <endpoint address="" behaviorConfiguration="App.secure.Admin.AdminAspNetAjaxBehavior" binding="webHttpBinding" contract="App.secure.Admin.Admin" />
            </service>
        </services>
    </system.serviceModel>
</configuration>

Thank you

Legends
  • 21,202
  • 16
  • 97
  • 123
Daniel
  • 605
  • 1
  • 8
  • 19
  • did u try to browse the svc in your browser to check if its working? – Legends Apr 15 '15 at 00:46
  • it is trying to open wcf test client. The error is Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata. – Daniel Apr 15 '15 at 00:55
  • post your web.config for the wcf service. Take a look at this: http://stackoverflow.com/questions/5199541/failed-to-add-a-service-service-metadata-may-not-be-accessible-make-sure-your – Legends Apr 15 '15 at 01:09
  • I created a seperate webapplication and tried adding the service. When I ran the application when svc file is highlighted, it was throwing the same error – Daniel Apr 15 '15 at 01:10
  • could not add all the related config in one comment, sorry for the brevity – Daniel Apr 15 '15 at 01:26
  • Check my answer, and especially take a look at the web.config I have posted. Do u have also put some auth restrictions to the Admin folder? Then u also need the appropriate permissions to access the svc. But first of all, after you have updated the web.config, right click on your svc file and choose view in browser. Before u do that, start fiddler to capture the request and response! In order to see if something fails. – Legends Apr 15 '15 at 10:34

2 Answers2

2

You need to add a service behaviour and an additional mex endpoint in order to get the svc metadata.

The config should look like this:

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <behaviors>
      <endpointBehaviors>
          <behavior name="AspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
        <behavior name="Call_WCF_WebService_REST_With_jQuery.service.AjaxServiceAspNetAjaxBehavior">
          <enableWebScript />                   
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
                <behavior name="MyAjaxSvcBehaviour">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="Call_WCF_WebService_REST_With_jQuery.service.AjaxService" behaviorConfiguration="MyAjaxSvcBehaviour">
        <endpoint address="" behaviorConfiguration="Call_WCF_WebService_REST_With_jQuery.service.AjaxServiceAspNetAjaxBehavior"
          binding="webHttpBinding" contract="Call_WCF_WebService_REST_With_jQuery.service.AjaxService" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>

The HTML:

<script>
    var svc = new AjaxService();
    var res = svc.DoWork();
    var x = 0;
</script>

The service:

namespace Call_WCF_WebService_REST_With_jQuery.service
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AjaxService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public Person DoWork()
        {
            // Add your operation implementation here
            return new Person() { Age = 12, Name = "Jo" };
        }

        // Add more operations here and mark them with [OperationContract]
    }
}
Legends
  • 21,202
  • 16
  • 97
  • 123
1
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ChartImageHandler" />
      <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </handlers>
  </system.webServer>
  <connectionStrings>
  database connections---
  </connectionStrings>
  <system.web>
    <httpHandlers>
      <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
    </httpHandlers>
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /></controls>
    </pages>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="AjaxControlToolkit, Version=4.5.7.1213, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5" />
    <!--<authentication mode="Forms">
      <forms defaultUrl="~/default.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="20" />
    </authentication>-->
    <!--Start of windows authentication -->
    <authentication mode="Windows" />

       <authorization>
            roles
       <deny users="*" />
      </authorization>

    <roleManager defaultProvider="WindowsProvider" enabled="true" cacheRolesInCookie="false">
      <providers>
        <add name="WindowsProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
      </providers>
    </roleManager>
    <!--<pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>-->

    <sessionState timeout="120"></sessionState>
  </system.web>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=C:\TempImageFiles\;" />
  </appSettings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.WindowsAzure.Storage" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.1.0.4" newVersion="2.1.0.4" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="HtmlAgilityPack" publicKeyToken="bd319b19eaf3b43a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.4.9.0" newVersion="1.4.9.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="App.AdminSvcAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
        <behavior name="App.secure.Admin.AdminAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <services>
      <service name="App.AdminSvc">
        <endpoint address="" behaviorConfiguration="App.AdminSvcAspNetAjaxBehavior"
          binding="webHttpBinding" contract="App.AdminSvc" />
      </service>
      <service name="App.secure.Admin.Admin">
        <endpoint address="" behaviorConfiguration="App.secure.Admin.AdminAspNetAjaxBehavior"
          binding="webHttpBinding" contract="App.secure.Admin.Admin" />
      </service>
    </services>
  </system.serviceModel>
</configuration>
Daniel
  • 605
  • 1
  • 8
  • 19
  • I just implemented it as WCf post service as this was not working for me. Thank you for trying to help. – Daniel Apr 15 '15 at 23:34