【发布时间】:2014-09-18 00:35:34
【问题描述】:
我正在尝试在不修改 App.config 文件的情况下实现 WCF Rest 服务。
我的服务界面如下所示:
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/teststr/?string={aStr}")]
string TestString(string aStr);
}
Service 实现非常基础:
public class TestService : IService
{
public string TestString(string aStr = null)
{
Console.WriteLine("The Test() method was called at {0}"
+ "\n\rThe given string was {1}\n\r"
, DateTime.Now.ToString("H:mm:ss")
, aStr);
return aStr;
}
}
还有我运行一切的主程序:
// Step 1 Create a URI to serve as the base address.
Uri baseAddress = new Uri("http://localhost:8000/ServiceSample/");
// Step 2 Create a ServiceHost instance
ServiceHost selfHost = new ServiceHost(typeof(TestService), baseAddress);
try
{
// Step 3 Add a service endpoint.
selfHost.AddServiceEndpoint(typeof(IService), new WebHttpBinding(),
"TestService");
// Step 4 Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
// Step 5 Start the service.
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
当我运行它并输入以下网址时:
http://localhost:8000/ServiceSample/TestService/teststr/?string=thisisatest
我收到这条消息:
// The message with To '...' cannot be processed at the receiver, due to an
// AddressFilter mismatch at the EndpointDispatcher. Check that the sender
// and receiver's EndpointAddresses agree.
我看过类似的 SO 问题,建议 I add the <webHttp/> behavour(但 Step 4 不是已经这样做了吗?),其他人说 adding [ServiceBehavior..]。这些都不起作用,我没有发现相关的 SO 问题有用。
我需要修改 App.config 文件吗?我在这里做错了什么?
【问题讨论】:
-
看起来您正在尝试对 SOAP 服务进行 RESTful 调用,但这是行不通的 - 它们是两种完全不同的 Web 服务风格。尝试使用 WebServiceHost 而不是
ServiceHost看看是否有帮助。 -
感谢@Tim 做到了!我怎么会错过呢。