我的restful wcf Web服务是用Visual Studio 2010编写的。
这是Service1.svc.cs中的代码
namespace ContactRegistration
{
public class Service1 : IService1
{
public string JSONDataPost(Contact ContactObject)
{
//code to put the data in the database goes here
//we'll pretend it all went okay and return
return "0|Data added okay";
}
}
}
这是IService1.cs中的代码
namespace ContactRegistration
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/JSONDataPost",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string JSONDataPost(Contact ContactObject);
}
[DataContract]
public class Contact
{
[DataMember]
public string Organisation { get; set; }
[DataMember]
public string FirstName { get; set; }
public Contact(string organisation, string firstName)
{
this.Organisation = organisation;
this.FirstName = firstName;
}
}
}
这是网络配置。
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="ContactRegistration.Service1Behavior"
name="ContactRegistration.Service1">
<endpoint address="" binding="webHttpBinding"
contract="ContactRegistration.IService1" behaviorConfiguration="web">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ContactRegistration.Service1Behavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
当我从Web应用程序调用Web服务时,我使用的URI是:
Uri地址=新的Uri(“http://www.myserver/ContactRegistration/Service1.svc/JSONDataPost”);
我收到了来自服务器的错误请求400。
[OperationContract]是否正确写入? URITemplate有什么问题吗?我今天看了几十个例子,他们似乎将URITemplate作为'/ NameOfMethod'就是我所做的。
编辑:用于显示调用方式开始的代码 Uri地址=新的Uri(“http://www.myserver/ContactRegistration/Service1.svc/JSONDataPost”);
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
// Create the data we want to send
Contact myContact = new Contact();
myContact.Organisation = "Society of Fruit Flies";
myContact.FirstName = "Fred";