【发布时间】:2017-03-10 00:17:02
【问题描述】:
我一直在关注教程here 并尝试使用 WCF 托管一个简单的 REST 服务器。基本上,我按照教程中的描述创建了 WCF 接口和类文件:
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GET/{msg}/{msg2}")]
string GetRequest(string msg, string msg2);
[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "/PUT/{msg}")]
void PutRequest(string msg, Stream contents);
}
以及具体的类:
class Service : IService
{
static string Message = "Hello";
public string GetRequest(string msg, string msg2)
{
return Message + msg + msg2;
}
public void PutRequest(string msg, Stream contents)
{
Service.Message = msg + msg + msg;
string input = new StreamReader(contents).ReadToEnd();
Console.WriteLine("In service, input = {0}", input);
}
}
这 2 个 WCF 服务类在我创建的控制台应用程序中完美运行。这是“主要”的样子。 当我向控制台应用程序提交 GET 请求时,我得到 200 OK:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var host = new ServiceHost(typeof(Service)))
{
var ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), new Uri("http://1.10.100.126:8899/MyService"));
ep.EndpointBehaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Service is running");
Console.ReadLine();
host.Close();
}
}
}
}
但是,当我想在 WPF 应用程序 中使用这两个类时,它们不再起作用了。这是 WPF 应用程序的 MainWindow 类。 当我向 WPF 应用程序提交 GET 请求时,我收到错误 502 BAD GATEWAY:
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
using (var host = new ServiceHost(typeof(Service)))
{
var ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), new Uri("http://1.10.100.126:8899/MyService"));
ep.EndpointBehaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Service is running");
Console.ReadLine();
host.Close();
}
}
}
}
如何使这 2 个 WCF 类与一个简单的空 WPF 应用程序项目一起工作? 为什么这 2 个 WCF 类适用于空的控制台应用程序项目,而不适用于空的 WPF 应用程序项目?
【问题讨论】:
-
Console.ReadLine在这种情况下不会导致线程暂停。所以host打开后会立即关闭。您可能应该将host.Close移动到某个“退出”按钮。您需要将host变量设为成员变量才能使其工作。 -
我试图从我的 WPF 应用程序中彻底删除 Console.Readline() 和 host.Close() 行。我仍然得到502,但不要认为主机在打开后立即关闭是原因。也许主机只是没有打开?
-
你能说明你是如何处理你的
GET请求的吗? -
您还需要删除
using语法。using将处理您的host对象。另外,我认为您应该将host设为实例变量。 -
@Alisson 我使用 Fiddler 测试我的 GET 请求,所以基本上是对“1.10.100.126:8899/MyService/GET/a/b”的 GET 请求,这对于 WPF 和控制台都适用