我正在尝试为我正在制作的网站测试我的WCF服务。我使用jQuery来调用服务($.getJSON()
),但我一直在网站上收到连接拒绝错误。
所以当我部署到计算机时,我检查了它所做的网站,我的方法“GetData()”甚至没有列出。它只列出了服务本身的名称。我一般都很擅长使用WCF,所以请怜悯:')在Windows Studio打开的测试客户端中,甚至没有列出我的服务:
当我尝试添加它时,它表示服务已成功添加,但没有显示。今天早些时候,我看到了列表中的方法,但由于我搞砸了,不得不删除整个项目。
Web.config看起来像这样:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- 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="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
<behavior name="enableScriptBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="PUendeligWebService.ExampleService">
<endpoint address="" binding="webHttpBinding"
contract="PUendeligWebService.ExampleServiceInterface" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
接口:
[ServiceContract]
public interface ExampleServiceInterface
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
String GetData();
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
服务:
public class ExampleService : ExampleServiceInterface
{
public String GetData()
{
Random ran = new Random();
TestClass[] tc = new TestClass[5];
TestClass tc1 = new TestClass();
tc1.TheText = "First Text " + ran.Next();
tc1.TheOtherText = "First Other Text " + ran.Next();
TestClass tc2 = new TestClass();
tc2.TheText = "Second Text " + ran.Next();
tc2.TheOtherText = "Second Other Text " + ran.Next();
TestClass tc3 = new TestClass();
tc3.TheText = "Third Text " + ran.Next();
tc3.TheOtherText = "Third Other Text " + ran.Next();
TestClass tc4 = new TestClass();
tc4.TheText = "Fourth Text " + ran.Next();
tc4.TheOtherText = "Fourth Other Text " + ran.Next();
TestClass tc5 = new TestClass();
tc5.TheText = "Fifth Text " + ran.Next();
tc5.TheOtherText = "Fifth Other Text " + ran.Next();
tc[0] = tc1;
tc[1] = tc2;
tc[2] = tc3;
tc[3] = tc4;
tc[4] = tc5;
return JsonConvert.SerializeObject(tc);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
最后,只是为了好的衡量,这是我使用的jQuery:
$(function() {
$("input:button").click(function() {
$.getJSON("http://localhost:52535/ExampleService.svc/GetData?callback=?", function(data) {
alert(data);
});
});
});
答案 0 :(得分:1)
首先,如果您更改webInvoke属性会更好:
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
String GetData();
对此:
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate="/getData")]
String GetData();
运行你的服务并在浏览器中打开它,写下这样的URL:
http://host_name:port_number/service_name.svc/getData
之后你应该得到你的数据(如果每个方面都没问题)
当我尝试添加它时,它表示服务成功 补充说,但没有任何表现。今天早些时候我看到了列表中的方法 但由于我搞砸了,不得不删除整个项目。
我认为这是因为您在Web配置文件中设置的webHttpBinding(使您的服务更加安静)。 Usualy测试客户端为SOAP服务生成调用方法。
答案 1 :(得分:1)
(想写一个评论,但它已经很长了......) 要创建简单的休息服务,您必须执行以下几个步骤:
1)定义服务方法和界面:
namespace CoreAuroraService.Services
{
[DataContract]
public class Patient
{
[DataMember]
public String LastName{get;set;}
[DataMember]
public string FirstName{get;set;}
}
[ServiceContract]
public interface IPatientService
{
[OperationContract]
[WebGet(UriTemplate = "/GetAllPatients", ResponseFormat = WebMessageFormat.Json)]
List<Patient> GetAllPatients();
[OperationContract]
[WebInvoke(UriTemplate = "/Create", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
bool CreatePatient();
[OperationContract]
[WebInvoke(UriTemplate = "/Update", Method = "PUT", ResponseFormat = WebMessageFormat.Json)]
bool UpdatePatient(Guid patientGuid);
[OperationContract]
[WebInvoke(UriTemplate = "/Delete", Method = "DELETE", ResponseFormat = WebMessageFormat.Json)]
bool DeletePatient(Guid patientGuid);
}
public class PatientService : IPatientService
{
public List<Patient> GetAllPatients()
{
var patient = new Patient() { FirstName = "Jeem", LastName = "Street" };
var patients = new List<Patient> { patient };
return patients;
}
public bool CreatePatient()
{
// TODO: Implement the logic of the method here
return true;
}
public bool UpdatePatient(Guid patientGuid)
{
// TODO: Implement the logic of the method here
return true;
}
public bool DeletePatient(Guid patientGuid)
{
// TODO: Implement the logic of the method here
return true;
}
}
}
2)现在您必须定义服务的行为。为此,您必须更改服务项目中的配置文件。在此文件中,您必须定义服务行为以及使您的服务更加安静的其他设置。为此,请在 serviceModel 块中粘贴下一个代码:
<services>
<service name="CoreAuroraService.Services.PatientService">
<endpoint address="" behaviorConfiguration="rest" binding="webHttpBinding" bindingConfiguration="maxStream" contract="CoreAuroraService.Services.IPatientService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<host>
<baseAddresses>
<add baseAddress="https://localhost/Services/PatientService.svc"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="rest">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<!-- 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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
3)现在让我们编写一个方法,从javascript调用我们的服务:
<script>
function GetP() {
// Now I need to send cross domain request to the service because my services hosted in another project
// Tested in IE 11
var url = "http://localhost:29358/Services/PatientService.svc/GetAllPatients";
$.ajax({
type: 'GET',
dataType: "text",
url: url,
success: function (responseData, textStatus, jqXHR) {
console.log("in");
var data = JSON.parse(responseData);
console.log(data);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
}
</script>