【发布时间】:2014-01-12 21:16:15
【问题描述】:
我是使用 WCF 服务的新手,希望您能帮助我解决一些调用外部 REST Web 服务的问题。我创建了两个应用程序来尝试测试我的服务。
- 用于测试我的类库的控制台应用程序
- 托管我的服务的 umbraco 应用程序
两个本地主机。
这是我的服务代码:
namespace HorecaWebservices.Webservices
{
[ServiceContract]
public interface IWS_Test
{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
Agenda GetAgenda(String mobileAppKey);
}
}
namespace HorecaWebservices.Webservices
{
public class WS_Test : IWS_Test
{
public Agenda GetAgenda(String mobileAppKey)
{
return BL_Agenda.GetAgenda(mobileAppKey);
}
}
}
我的服务的网络配置:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="true"
defaultOutgoingResponseFormat="Json">
</standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
<services>
<service name="HorecaWebservices.Webservices.WS_Test"
behaviorConfiguration="MyServiceTypeBehaviors">
<endpoint address="" binding="wsHttpBinding"
contract="HorecaWebservices.Webservices.IWS_Test"/>
<endpoint contract="IMetadataExchange"
binding="mexHttpBinding" address="mex"/>
</service>
</services>
</system.serviceModel>
这是我的控制台应用程序中调用服务方法的代码:
public static class BL_Agenda
{
public static Agenda GetAgenda()
{
Agenda agenda = new Agenda();
WebRequest request = WebRequest.Create("http://localhost:63462/Webservices/WS_Test.svc/GetAgenda");
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
string postData = "{\"mobileAppKey\":\"HEMDZ\"}"; //encode your data
using (Stream s = request.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(s))
sw.Write(postData);
s.Close();
}
try
{
using (Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
var jsonData = sr.ReadToEnd();
agenda = JsonConvert.DeserializeObject<Agenda>(jsonData);
}
s.Close();
}
}
catch (WebException e)
{
agenda = null;
WebExceptionStatus status = e.Status;
Console.WriteLine(status.ToString());
}
return agenda;
}
现在,每当我运行此代码时,request.GetResponse() 都会抛出 System.Net.WebException "(415) 无法处理消息,因为内容类型 'application/json; charset=utf-8' 不是预期的类型'应用程序/soap+xml; charset=utf-8'"
经过几个小时试图找出问题所在,我仍然无法弄清楚。有人可以帮我解决这个问题吗?
【问题讨论】:
-
您已在
web.config中定义了您的 service 以使用WsHttpBinding,这是一个基于 XML 的 SOAP 绑定 - 而不是 JSON -based REST-binding 您似乎期望在客户端。对于 REST,请在服务器端使用webHttpBinding