如何在 jQuery 中使用 WCF 方法

Posted

技术标签:

【中文标题】如何在 jQuery 中使用 WCF 方法【英文标题】:How to use WCF method with jQuery 【发布时间】:2018-04-15 18:41:36 【问题描述】:

我正在测试我的第一个 WCF 服务。它只有一种方法,等于作为参数给出的两个值并返回结果。

当我使用Visual Studio提供的测试客户端时它工作正常,但是当我通过使用jQuery开发自己的JS客户端时,我不知道如何读取数据或如何调用该方法来获取和显示一个警报。

代码如下:

ImiServicio.cs

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

namespace primerwcf


    [ServiceContract]
    public interface ImiServicio
    
        [OperationContract]
        int getSuma(int numero1, int numero2);
    

miServicio.svc.cs

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

namespace primerwcf


    public class miServicio : ImiServicio
    
        public int getSuma(int numero1, int numero2)
        
            return numero1+numero2;
        
    

网络配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>

    <appSettings>
        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    </appSettings>
    <system.web>
        <compilation debug="true" targetFramework="4.6.1" />
        <httpRuntime targetFramework="4.6.1"/>
    </system.web>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>    
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <directoryBrowse enabled="true"/>
    </system.webServer>
</configuration>

Javascript/Jquery 代码

$("#b1").click(function()

    $.ajax(
    

         type: "GET",
         url:"http://localhost:50664/miServicio.svc",
         data:

             numero1:2,
             numero2:6
         ,
         dataType: "xml" ,
         success:function(response)
         
             alert("ok "+response);

         ,
         error:function()

             alert("error");
         


    );

);

当我简单地展示时

alert(response);

它返回一个对象 XMLDocument

但是当我尝试使用时

$.parseXML(response);

它返回空值。

我在 ajax() 方法中将 dataType 更改为“text”,但我只获得了粘贴地址时将在浏览器中显示的 html 代码。

我也尝试过这样调用方法:

response.getSumarResult

但它返回未定义。

我查看了这些来源,其中包括:

https://www.codeproject.com/Questions/544312/HowplustoplusreadplusXMLplusFileplusinplusaplusWCF

http://www.developerin.net/a/62-Code-Snippets/49-Calling-WCF-services-using-Jquery

由于所咨询的大多数教程都很旧,我不知道是否必须像某些网站建议的那样配置 webConfig 文件,因为我似乎从服务中成功获取了数据。

【问题讨论】:

您应该通过 jQuery 调用获得一个对象,并且您不必解析 xml。你能与结果交互吗,比如alert(response.result); @Ricardo Pontual 不,当我使用 alert(reponse); 时它返回对象 XMLDocument,但是当我使用 alert(response.result); 时它返回 undefined @Ricardo Pontual 以防万一它有用,当我指定没有 dataType 并且我执行 alert(response); 时,它会返回当我在浏览器上提供服务地址时将显示的所有 HTML 文档(说明创建一个客户端,等等)。 【参考方案1】:

经过多次测试和努力,我设法解决了它。我将在这里发布我为其他有同样问题的人所做的事情。

注意我正在使用 VS 2017:

-首先,我把ImiServicio.cs和miServicio.svc.cs都删了

-选择当前项目/添加新元素,然后包含启用 AJAX 的新 WCF 服务。您不需要以这种方式创建界面。

-在新的 WCF 上,我将此代码添加到 getSuma() 方法中:

**[WebGet(ResponseFormat = WebMessageFormat.Xml)]**
    public int getSuma(int numero1, int numero2)
        
            WebOperationContext.Current.OutgoingResponse.ContentType =  "text/xml";
            return numero1 + numero2;
        

方法主体中的“WebOperationContext...”行似乎不是强制性的,但是VS建议包含它,所以我做了。

-现在,我们转到 jQuery 代码并更改以下行:

url:"http://localhost:50664/miServicio.svc"

注意我没有在旧代码上调用该方法,所以这样做:

url:"http://localhost:50664/miServicio.svc/getSuma"

-接下来,在成功函数上,替换这个:

alert("ok "+ response);

有了这个:

/*use the text() jQuery method to obtain the value returned by the method*/
alert("ok "+$(response).text());

重要提示:我仍然不知道如何通过代码启用 CORS,因此目前我不得不使用 firefox extension 来避免这个问题。如果您不启用,尽管响应正常(状态 200),您仍会收到错误消息。

【讨论】:

您基本上是在这里用 jquery 解析XMLDocument(在$(response).text() 部分)。其余的答案真的不需要。这适用于简单的原始返回值......如果您返回任何具有序列化属性的类或结构,您也必须解析它们。如果您不需要需要 XML,我建议切换到 JSON 响应,并且您的客户端将始终是 javascript,因为它已经为您解析(JSON 是现代 javascript 的本机,而您可以直接使用响应值)

以上是关于如何在 jQuery 中使用 WCF 方法的主要内容,如果未能解决你的问题,请参考以下文章