使用JQuery Ajax调用WCF REST服务无法正常工作

时间:2012-12-07 04:26:26

标签: wcf

我正在学习WCF服务。我试图从Jquery调用RESTful服务。我的服务如下

服务类

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

namespace RESTfulServiceLib
{
[AspNetCompatibilityRequirements(RequirementsMode
    = AspNetCompatibilityRequirementsMode.Allowed)]
public class RestFullService : IRestFullService
{
    public string Welcome(string Name)
    {
        return  "Welcome to Restful Service " + Name;
    }
}
}

接口

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;

namespace RESTfulServiceLib
{

[ServiceContract]

public interface IRestFullService
{
    [OperationContract]
    [WebInvoke(UriTemplate="/Welcome/{Name}",Method="GET",ResponseFormat=WebMessageFormat.Json)]
    string Welcome(string Name);
}
}

我创建了一个服务主机,svc文件就像这样

<%@ ServiceHost Language="C#" Debug="true" Service="RESTfulServiceLib.RestFullService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

我有以下配置设置

<configuration>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>

<system.serviceModel>
    <behaviors>
        <endpointBehaviors>
            <behavior name="EndPBhvr">
                <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
                    faultExceptionEnabled="true" />

            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="SvcBhvr">
                <serviceMetadata httpGetEnabled="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <services>
        <service name="RESTfulServiceLib.RestFullService">
            <endpoint address="" behaviorConfiguration="EndPBhvr"
                binding="webHttpBinding" bindingConfiguration="" name="EP1"
                contract="RESTfulServiceLib.IRestFullService" />
        </service>
    </services>
</system.serviceModel>
</configuration>

运行应用程序后,当我浏览网址“http:// localhost:2319 / RESTFullService.svc / welcome / Mahesh”时 它将值返回为

"Welcome to Restful Service Mahesh"

我试图使用Jquery调用此服务。但我得到了

error 200 undefined

脚本如下

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.4.min.js"></script>
<script >
function ajaxcall()
{
    $.ajax({
        url: "http://localhost:2319/RESTFullService.svc/welcome/mahesh",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType:"jsonp",
        data:{},
        processdata : true,
        success: function(response)
        {
            var data= response.d;
            alert(data);
        },

        error: function(e)
        {
            alert('error '+e.status + ' ' + e.responseText);
        }
    });
}
$().ready(function(){
    $('#btntest').click(ajaxcall);
})  
</script>
</head>
<body>
<button id="btntest" >Click Me</button>
</body>
</html>

我的编码有什么问题?请帮帮我......

由于

马赫什

3 个答案:

答案 0 :(得分:1)

在jQuery的成功中,你已经使用了

// var data= response.d;

但是你没有返回有效的json。 你的回复中没有“d”。

答案 1 :(得分:0)

这是由于跨域问题。我在配置文件中做了一些更改,它运行良好

更改后的配置文件。添加了具有crossDomainScriptAccessEnabled =“true”的新绑定配置并添加到端点。并把aspNetCompatibilityEnabled =“false”

<configuration>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>

<system.serviceModel>
    <standardEndpoints />
    <bindings>
        <webHttpBinding>
            <binding name="Bind1" crossDomainScriptAccessEnabled="true" />
        </webHttpBinding>
    </bindings>
    <behaviors>
        <endpointBehaviors>
            <behavior name="EndPBhvr">
                <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
                    faultExceptionEnabled="true" />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="SvcBhvr">
                <serviceMetadata httpGetEnabled="false" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
       <serviceHostingEnvironment aspNetCompatibilityEnabled="false" />
    <services>
        <service behaviorConfiguration="SvcBhvr" name="RESTfulServiceLib.RestFullService">
            <endpoint address="" behaviorConfiguration="EndPBhvr" binding="webHttpBinding"
                bindingConfiguration="Bind1" name="EP1" contract="RESTfulServiceLib.IRestFullService" />
        </service>
    </services>
</system.serviceModel>
</configuration>

修改过的脚本,我添加了“?callback =?”在URL的末尾以JSON而不是JSONP获取输出。 JSONP将在不提供URL

的回调的情况下工作
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" language="javascript">
    function ajaxcall()
    {
        $.ajax({
            url: "http://localhost:2319/RESTFullService.svc/welcome/mahesh?calback=?",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            success: function (response) {
                var data = response;
                alert(data);
            },

            error: function (e) {
                alert('error ' + e.status + ' ' + e.responseText);

            }
            });
    }

    $().ready(function(){
        $('#btntest').click(ajaxcall);
    })  
</script>
</head>
<body>
    <button id="btntest" >Click Me</button>
</body>
</html>

感谢我的同事Cofoft Labs的Mrs.Poorani帮我解决了这个问题

答案 2 :(得分:0)

function CallService(sucessData) {
$.ajax({
    // Add code for Cross Domain
    headers: getHeaders(),
    type: varType, //GET or POST or PUT or DELETE verb
    url: varUrl, // Location of the service
    data: varData, //Data sent to server
    contentType: varContentType, // content type sent to server
    dataType: varDataType, //Expected data format from server
    processdata: varProcessData, //True or False
    crossDomain: true,
    cache: varCache,
    timeout: 200000,
    success: sucessData,
    error: function (xhr) {// When Service call fails
        fancyAlert("Error: " + xhr.responseText);
        //fancyAlert('Error occured in Service Call');
    }
});
}