【发布时间】: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 文档(说明创建一个客户端,等等)。
标签: javascript c# jquery .net wcf