0

こんにちは、私は何らかの理由で 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>

Java スクリプト

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

2 に答える 2

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>
于 2014-08-19T05:17:01.367 に答える
0

service/serviceメソッドにScriptService/ScriptMethod属性がないようです。

于 2013-03-20T20:44:28.850 に答える