使用javascript代码中无法访问的AjaxEnabled WCF服务

时间:2015-04-14 23:12:39

标签: javascript c# asp.net wcf asp.net-ajax

我已按照以下链接在我的项目中创建启用了ajax的服务 https://msdn.microsoft.com/en-us/library/bb924552(v=vs.110).aspx

我的Asp.Net网络表单项目在不同的文件夹中有多个表单。 admin文件夹包含管理表单。我从admin文件夹创建了wcf服务,代码如下

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

在我的webform中,我无法添加单独的ScriptManager,因为我已经在表单中使用了ToolkitScriptManager。

我已添加服务参考,如下所示

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

当我尝试调用wcf服务调用时,它无法在wcf服务中实例化该类

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

当我运行应用程序时

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

我已经尝试将WCf服务移动到根文件夹并尝试调用它,但是它给出了同样的错误。

add.aspx.cs文件,我正在使用

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

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>

谢谢

2 个答案:

答案 0 :(得分:2)

您需要添加服务行为和其他mex端点才能获取svc元数据。

配置应如下所示:

<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>

HTML:

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

服务:

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]
    }
}

答案 1 :(得分: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>