【问题标题】:Unable to pass parameter to REST/WCF service using JSONP无法使用 JSONP 将参数传递给 REST/WCF 服务
【发布时间】:2012-01-07 06:21:21
【问题描述】:

我想使用 JSONP 调用 WCF 服务。有两种方法, 1、“Hello”方法,不带任何参数。这工作正常 2. "Hello1" 方法接受一个字符串参数。这不能正常工作。它应该返回我传递的值。

下面是代码sn-p

服务器代码

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfService1
{

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

        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public string Hello()
        {
            return "I got the call";
        }

        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public string Hello1(string str)
        {
            return "Hi, you passed me " + str;
        }

    }

}

网页配置代码

    <?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="None" />
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
      </webScriptEndpoint>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="True"
          automaticFormatSelectionEnabled="true" />
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>
</configuration>

客户端代码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="JS/JQuery.js" type="text/javascript"></script>
    <script type="text/javascript">


        var Type;
        var Url;
        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: Data, //Data sent to server
                contentType: ContentType, // content type sent to server
                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(result) {
            alert('test');
            alert('Service call failed: ' + result.status + '' + result.statusText);
            Type = null;
            Url = null;
            Data = null;
            ContentType = null;
            DataType = null;
            ProcessData = null;
        }

        function Hello() {
            var uesrid = "1";
            Type = "GET";
            Url = "http://localhost:52136/Service1.svc/Hello";
            DataType = "jsonp"; ProcessData = false;
            method = "Hello";
            //debugger;
            CallService();
        }

        function Hello1() {
            debugger;
            var uesrid = "1";
            Type = "GET";
            ContentType = "application/json; charset=utf-8";
            Url = "http://localhost:52136/Service1.svc/Hello1";
            DataType = "jsonp"; //ProcessData = false;
            method = "Hello1";
            Data = "{'str':'abc'}"; //"{'Input':'a123'}";//"{'StringValue':'1234'}"; 
            //debugger;
            CallService();
        }


        function ServiceSucceeded(result) {
            debugger;
            if (DataType == "jsonp") {
               alert(result); /* Problem, While calling 'Hello1' method I do not get the value in the return string*/
            }
        }

        function ServiceFailed(xhr) {
            alert(xhr.responseText);
            if (xhr.responseText) {
                var err = xhr.responseText;
                if (err)
                    error(err);
                else
                    error({ Message: "Unknown server error." })
            }
            return;
        }

        $(document).ready(
         function () {
             try {
                 //Hello();
                 Hello1();
             } catch (exception) { }
         }
);

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <h1>
        JSONP Service Client Page</h1>
    </form>
</body>
</html>

在调用 Hello1 方法时,谁能告诉我代码有什么问题

阿图尔·苏雷卡

【问题讨论】:

    标签: wcf jsonp


    【解决方案1】:
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Web;
    
    namespace WcfService1
    {
    
        [ServiceContract(Namespace = "JsonpAjaxService")]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class Service1
        {
    
            [WebGet(ResponseFormat = WebMessageFormat.Json)]
            public string Hello()
            {
                return "I got the call";
            }
    
            [WebGet(BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "SetQuoteEntities?str={str}")]
            public string Hello1(string str)
            {
                return "Hi, you passed me " + str;
            }
    
        }
    
    }
    

    当我修改属性 webGet 它对我有用。

    【讨论】:

      【解决方案2】:

      尝试将数据作为对象而不是字符串传递:

      function Hello1() { 
          debugger; 
          var uesrid = "1"; 
          Type = "GET"; 
          ContentType = "application/json; charset=utf-8"; 
          Url = "http://localhost:52136/Service1.svc/Hello1"; 
          DataType = "jsonp"; //ProcessData = false; 
          method = "Hello1"; 
          Data = {str : 'abc'};
          //debugger; 
          CallService(); 
      } 
      

      【讨论】:

        猜你喜欢
        • 2012-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-31
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 2014-01-28
        相关资源
        最近更新 更多