2013-03-20 109 views
0

嗨,大家我想從一個javascript函數調用wcf服務出於某種原因asp.net不能識別命名空間並在運行時給我一個錯誤,任何幫助將不勝感激以下是代碼:無法從javascript調用wcf服務

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

回答

0

你似乎缺少您的服務/業務方法ScriptService/ScriptMethod屬性。

+0

任何想法,我應該用什麼,我的意思是,你能不能給我一個確切的語法放入文件? – CharlesMighty 2013-03-20 20:46:06

+1

我查閱了文檔,看起來對於WCF,您所要做的就是在您的方法中添加WebInvoke屬性:http://msdn.microsoft.com/en-us/library/bb412168.aspx – 2013-03-20 20:53:01

1

這裏我使用javascript調用簡單的Hello World從WCF

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和配置文件中共同命名「Service」。

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