我在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的JavaScript concole中看到,该响应是从WCF服务发送的(getomething方法的内容是" Hello"),但是我将获得以下控制台输出:
Loading
GetSomething:-1Resource interpreted as Script but transferred with MIME type application/json.
Object
parsererror
Error: jQuery1101030437586596235633_1390485791492 was not called
我的成功功能从未执行过。当我遵循与此类似的一些帖子时,我毫无疑问,它与内容类型有关,但是我找不到方法如何获得这项工作。有人可以帮我吗?
我自己解决了。问题是,在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>