我在WCF服务中调用一个简单方法时遇到问题。我被卡住了,我不知道如何解决这个问题。我将不胜感激。
我的WCF服务:
[ServiceContract]
interface IMyService
{
[OperationContract]
string GetSomething();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class MyService : IMyService
{
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "GetSomething",
BodyStyle = WebMessageBodyStyle.Bare)]
public string GetSomething()
{
return "Hello";
}
}
启动服务:
using (ServiceHost host = new ServiceHost(typeof(MyService)))
{
host.Open(); // end point specified in app config
Console.WriteLine("Hit Enter to quit.");
Console.ReadLine();
}
App.Config文件
<configuration>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webHttpBinding" crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
</bindings>
<services>
<service name="testWCF.MyService">
<endpoint address="http://localhost:8003/myservice"
binding="webHttpBinding"
contract="testWCF.IMyService"
behaviorConfiguration="webHttp"/>
</service>
</services>
</system.serviceModel>
</configuration>
关于WCF服务的全部内容。我的Web应用程序正在http://127.0.0.1:8085
上运行,以下是我从Web应用程序发送jQuery请求的方法:
$.ajax({
url: "http://127.0.0.1:8003/myservice/GetSomething?callback=?",
dataType: 'jsonp',
cache: false,
beforeSend: function () {
console.log("Loading");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
success: function (data) {
console.log('Success');
console.log(data);
},
complete: function () {
console.log('Finished all tasks');
}
});
我的回复如下: 我可以在我的chrome中看到我的chrome,该响应已经从WCF服务发送(GetSomething方法的内容是“Hello”),但我得到了以下控制台输出:
Loading
GetSomething:-1Resource interpreted as Script but transferred with MIME type application/json.
Object
parsererror
Error: jQuery1101030437586596235633_1390485791492 was not called
我的成功功能从未执行过。当我跟踪一些与此相似的帖子时,我发现它与Content-Type有关,但我找不到如何让这项工作。有人能帮助我吗?
答案 0 :(得分:1)
我自己解决了这个问题。问题出在App.config文件中。我添加了bindingConfiguration="webHttpBinding"
现在我的App.config文件是:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webHttpBinding" crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
</bindings>
<services>
<service name="testWCF.MyService">
<endpoint address="http://localhost:8003/myservice"
binding="webHttpBinding"
bindingConfiguration="webHttpBinding"
contract="testWCF.IMyService"
behaviorConfiguration="webHttp"/>
</service>
</services>
</system.serviceModel>
</configuration>