Asp.net 使用JQuery调用WCF服务时WCF服务调用失败
我正在使用asp.net。我已经在C#中创建了一个WCF服务,并托管在IIS服务器上。我在asp.net web应用程序中使用JQuery调用此服务。当我使用JQuery调用该服务时,它将返回error函数,并且在alert中有一条空消息 呼叫服务表单.aspx页面Asp.net 使用JQuery调用WCF服务时WCF服务调用失败,asp.net,wcf,jquery,Asp.net,Wcf,Jquery,我正在使用asp.net。我已经在C#中创建了一个WCF服务,并托管在IIS服务器上。我在asp.net web应用程序中使用JQuery调用此服务。当我使用JQuery调用该服务时,它将返回error函数,并且在alert中有一条空消息 呼叫服务表单.aspx页面 <script src="Script/jquery-1.10.2.min.js" type="text/javascript"></script> <script type="text/javasc
<script src="Script/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
function callService()
{
var value = 10;
$.ajax({
type: "POST",
url: "http://localhost/IISWCF/Service1.svc/getdata",
contentType: "application/json; charset=utf-8",
data: '{"value": "' + value + '"}',
dataType: "json",
processdata: true, //True or False
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + errorThrown);
},
success: function(msg) {
alert(msg.d);
}
});
}
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
callService();
})
</script>
IService1.cs文件
namespace WcfService1
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);
}
}
WCF Web.config文件
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WcfService1.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior">
<endpoint behaviorConfiguration="EndpBehavior" address="" binding="webHttpBinding" contract="WcfService1.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
请帮助我解决此问题。我添加了一些伪代码,可能也没有使用一些方法。但是您可以使用虚拟加倍方法测试代码。此外,您已经定义了endpointbehavior,但如果使用了它,则应将其应用于endpoint及其重要对象。参考我下面的例子
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface ICalculatorService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/DoubleUp/{val}")]
int DoubleUp(string val);
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json, UriTemplate="/{value}/{value1}")]
int AddValues(string value, string value1);
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ConcatenateString(string stringArray);
}
public class CalculationService : ICalculatorService
{
public int DoubleUp(string val)
{
return 2 * Convert.ToInt32(val);
}
public int AddValues(string value, string value1)
{
return Convert.ToInt32(value) + Convert.ToInt32(value1);
}
public string ConcatenateString(string stringArray)
{
string returnString = string.Empty;
returnString += stringArray;
return returnString;
}
}
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="JSONBinding"></binding>
</webHttpBinding>
<basicHttpBinding>
<binding name="basicHTTP">
<security mode="None">
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="basicBehavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="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="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="JSON">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="RestWCFService.CalculationService" behaviorConfiguration="basicBehavior">
<endpoint address="basic" binding="basicHttpBinding" contract="RestWCFService.ICalculatorService" bindingName ="basicHTTP"></endpoint>
<endpoint behaviorConfiguration="JSON" binding="webHttpBinding" bindingConfiguration="JSONBinding" contract="RestWCFService.ICalculatorService" name="JSONService"></endpoint>
</service>
</services>
<protocolMapping>
<add binding="basicHttpBinding" scheme="http"/>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
/* This is the code for accessing the service via REST call
WebClient client = new WebClient();
string s = client.DownloadString("http://localhost/RestWCFService/CalculationService.svc/DoubleUp/3");
Console.WriteLine("Response returned is:" + s);
*/
/*This is the section to access service via Proxy */
ChannelFactory<RestWCFService.ICalculatorService> client = new ChannelFactory<RestWCFService.ICalculatorService>();
client.Endpoint.Address = new EndpointAddress("http://localhost/RestWCFService/CalculationService.svc/basic");
client.Endpoint.Binding = new BasicHttpBinding();
RestWCFService.ICalculatorService service = client.CreateChannel();
int val = service.DoubleUp("2");
((IClientChannel)service).Close();
client.Close();
Console.WriteLine("Values returned is:" + val.ToString());
/*Programmatic access ends here */
Console.ReadLine();
如果您的服务工作正常,那么请尝试此JS,因为您的JS不适合此服务请求
<script type="text/javascript" language="javascript">
function callService() {
var value = 10;
$.ajax({
type: "GET",
url: "http://localhost/IISWCF/Service1.svc/GetData?value=1",
contentType: "application/json; charset=utf-8",
data: '{"value": "' + value + '"}',
dataType: "text",
processdata: false, //True or False
statusCode: {
404: function () {
alert("page not found");
},
200: function () {
alert('HTTP HIT WAS Good.');
},
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + errorThrown);
},
success: function (msg) {
alert(msg);
}
});
}
函数callService(){
var值=10;
$.ajax({
键入:“获取”,
url:“http://localhost/IISWCF/Service1.svc/GetData?value=1",
contentType:“应用程序/json;字符集=utf-8”,
数据:'{“值”:“'+value+'“}”,
数据类型:“文本”,
processdata:false,//True或false
状态代码:{
404:函数(){
警报(“未找到页面”);
},
200:函数(){
警报('HTTP命中率良好');
},
},
错误:函数(XMLHttpRequest、textStatus、errorshown){
警报(“错误:+错误抛出”);
},
成功:功能(msg){
警报(msg);
}
});
}
尝试使用本文中提到的说明,因为您可能需要JSON作为响应。似乎缺少WebGet和WebInvoke。我已经按照链接中提到的步骤进行了操作,问题没有得到解决。我用新问题编辑了我的问题。您能帮助我吗?将端点绑定更改为webHttpBinding我已将端点绑定更改为webHttpBinding,但问题仍未解决。任何帮助。当我在DoubleUp中添加整数作为参数时,它要求我转换为字符串。因此,请尝试通过直接点击URL来执行服务方法,然后进行Ajax测试。如果它直接工作,则Ajax调用存在一些问题。当我使用方法运行服务时,我收到错误,因为“由于EndpointDispatcher上的AddressFilter不匹配,收件人无法处理收件人为“”的消息。请检查发送方和收件方的EndpointAddresses是否一致。”但是如果我将端点webHttpBinding更改为wsbHttpBinding,那么页面将显示为空白。你能帮我一下吗?地址不匹配。URl中有一个不匹配的地方,比如说你在域中,正在获取,并且你在服务中指定了localhost。您可以通过添加[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]来删除它,但这并不是一个适用于所有请求的好做法。我已经添加了[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)],并将错误作为由于EndpointDispatcher上的ContractFilter不匹配,无法在接收方处理具有操作“”的消息。这可能是因为合同不匹配(发送方和接收方之间的操作不匹配)或发送方和接收方之间的绑定/安全不匹配。检查发送方和接收方是否具有相同的合同和相同的绑定(包括安全要求,例如消息、传输、无)。“需要帮助吗?您的服务是否直接起作用?请使用我为您的服务粘贴的代码。如果无法访问该服务,请使用最新的代码库编辑您的问题。是的,链接工作正常,我正在获取输出。但我的jqeruy电话不起作用。我用新的问题更新了我的问题。另外,我在web.config文件中得到了标记的错误,所以我已经删除了它。任何帮助。
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate="/GetData?value={value}")]
string GetData(int value);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WcfService1.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior">
<endpoint behaviorConfiguration="EndpBehavior" address="" binding="webHttpBinding" contract="WcfService1.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
http://localhost/IISWCF/Service1.svc/GetData?value=1
<script type="text/javascript" language="javascript">
function callService() {
var value = 10;
$.ajax({
type: "GET",
url: "http://localhost/IISWCF/Service1.svc/GetData?value=1",
contentType: "application/json; charset=utf-8",
data: '{"value": "' + value + '"}',
dataType: "text",
processdata: false, //True or False
statusCode: {
404: function () {
alert("page not found");
},
200: function () {
alert('HTTP HIT WAS Good.');
},
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + errorThrown);
},
success: function (msg) {
alert(msg);
}
});
}