【问题标题】:Unable to call wcf service from javascript无法从 javascript 调用 wcf 服务
【发布时间】:2013-03-20 20:40:02
【问题描述】:

大家好,由于某种原因,我试图从 javascript 函数调用 wcf 服务,asp.net 无法识别名称空间并在运行时给我一个错误,任何帮助将不胜感激以下是代码:

默认aspx页面

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WeatherService.svc"/>
        </Services>
    </asp:ScriptManager>

    Enter a zipcode:
    <input id="zipCodeInput" type="text" />
    <br/>
    <input id="getForecastButton" type="button" value="Get Forecast" onclick="onGetForecast()"/>
    <br/>



 <div id="resultsDiv">

    </div>
</form>

Javasript

 <script language="javascript" type="text/javascript">
    function onGetForecast() {
        var zip = document.getElementById("zipCodeInput").value;
        //alert(zip);

        UltimateServices.GetForecast(zip, onGetForecastComplete, onGetForecastError, zip);


    }



    function onGetForecastComplete(result, userData) {
        document.getElementById("resultsDiv").innerHTML = "Weather for " + userData + " is going to be " + result;
    }

    function onGetForecastError(err) {
        alert("There was a error " + err.get_message());
    }
</script>

WeatherService.cs 文件(代码隐藏)

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Runtime.Serialization;
 using System.ServiceModel;
 using System.ServiceModel.Activation;
 using System.ServiceModel.Web;
 using System.Text;

 [ServiceContract(Namespace = "UltimateServices")]
 [AspNetCompatibilityRequirements(RequirementsMode =         AspNetCompatibilityRequirementsMode.Allowed)]
 public class WeatherService
 {

private static Random _rand = new Random();


[OperationContract]
public string GetForecast(string zipcode)
{
    string forecast = "";
    switch(_rand.Next(3))
    {
        case 0:
            forecast = "Sunny and Warm";
            break;

        case 1:
            forecast = "Chilly and overcast";
            break;

        case 2:
            forecast = "Hot and humid";
            break;
    }
    return forecast;
}

// Add more operations here and mark them with [OperationContract]

}

web.config 文件

 <system.serviceModel>
<behaviors>
  <endpointBehaviors>
    <behavior name="WeatherServiceAspNetAjaxBehavior">
      <enableWebScript />
    </behavior>
  </endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
  multipleSiteBindingsEnabled="true" />
<services>
  <service name="WeatherService">
    <endpoint address="" behaviorConfiguration="WeatherServiceAspNetAjaxBehavior"
      binding="webHttpBinding" contract="WeatherService" />
  </service>
</services>
  </system.serviceModel>

【问题讨论】:

    标签: javascript asp.net wcf call


    【解决方案1】:

    我在这里使用 javascript 从 WCF 调用简单的 hello world

    Service.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;`
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    using System.ServiceModel.Activation;
    

    // 注意:您可以使用“重构”菜单上的“重命名”命令将代码、svc 和配置文件中的类名“服务”一起更改。

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
     [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public string helloworld(string name)
        {
            name = "Hello " + name;
            return  name;
        }
    }
    

    web.config

    <?xml version="1.0"?>
    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.0"/>
      </system.web>
      <system.serviceModel>
        <services>
          <service name="Service" behaviorConfiguration="DefaultBehavior">
            <endpoint address="" binding="webHttpBinding" contract="IService" name="RunningBarbus.Services.RunningBarbusService" behaviorConfiguration="AjaxBehavior">
              <identity>
                <dns value="localhost"/>
              </identity>
            </endpoint>
            <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
          </service>
        </services>
        <bindings>
          <webHttpBinding>
            <binding crossDomainScriptAccessEnabled="true">
              <security mode="None"/>
            </binding>
          </webHttpBinding>
        </bindings>
        <behaviors>
          <serviceBehaviors>
            <behavior name="DefaultBehavior">
              <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
              <serviceMetadata httpGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="AjaxBehavior">
              <!--<enableWebScript/>-->
              <webHttp  helpEnabled="true" automaticFormatSelectionEnabled="false" />
            </behavior>
          </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
        <standardEndpoints>
          <webScriptEndpoint>
            <standardEndpoint crossDomainScriptAccessEnabled="true" name="">
            </standardEndpoint>
          </webScriptEndpoint>
        </standardEndpoints>
       </system.serviceModel>
      <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="access-control-allow-headers" value="content-type, Accept" />
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
            <add name="Access-Control-Max-Age" value="1728000" />
          </customHeaders>
        </httpProtocol>
        <modules runAllManagedModulesForAllRequests="true"/>
    
      </system.webServer>
    </configuration>
    

    javascript 代码

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="jsonp.aspx.cs" Inherits="jsonp" %>
    
    <!DOCTYPE html >
    
    <html>
    <head runat="server">
        <title></title>
     <script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            var name="";
            var Type;
            var Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?name=world";
            var Data;
            var ContentType;
            var DataType;
            var ProcessData;
            var method;
            //Generic function to call WCF  Service
            function CallService() {
                $.ajax({
                    type: Type, //GET or POST or PUT or DELETE verb
                    url: Url, // Location of the service
                   // data: name, //Data sent to server
                    contentType: ContentType, // content type sent to server
                    //data: '[{"name":"' + name + '"}]',
                    dataType: DataType, //Expected data format from server
                    processdata: ProcessData, //True or False
                    success: function (msg) {//On Successfull service call
                        ServiceSucceeded(msg);
                    },
                    error: ServiceFailed// When Service call fails
                });
            }
            function ServiceFailed(xhr) {
                alert(xhr.responseText);
                if (xhr.responseText) {
                    var err = xhr.responseText;
                    if (err)
                        error(err);
                    else
                        error({ Message: "Unknown server error." })
                }
                return;
            }
            function ServiceSucceeded(result) {
                debugger;
                if (DataType == "jsonp") {
                    alert(result);
                    resultObject = result.helloworld;
                    var string = result.name ;
                    alert(string);
                }
            }
            function helloworld() {
                debugger;
                var uesrid = "";
                Type = "GET";
                // Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?'"+uesrid+'"';
                Url = Url;
    
                DataType = "jsonp"; ProcessData = false;
                method = "helloworld";
                CallService();
            }
    
            $(document).ready(
             function () {
    
                 helloworld();
             }
    );
    
        enter code here
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        </div>
        </form>
    </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      您的服务/服务方法似乎缺少 ScriptService/ScriptMethod 属性。

      【讨论】:

      • 知道我应该使用什么,我的意思是你能给我一个确切的语法来放入文件吗?
      • 我查阅了文档,似乎对于 WCF,您所要做的就是在您的方法中添加 WebInvoke 属性:msdn.microsoft.com/en-us/library/bb412168.aspx
      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多