[英]WCF REST Service hosted in Console Application minimum example
I've just started working with WCF and tried creating a small REST HTTP service. 我刚刚开始使用WCF,并尝试创建一个小的REST HTTP服务。 If it is hosted in the IIS, it works fine.
如果它托管在IIS中,则可以正常工作。 However now I am trying to host it in a console application.
但是现在我试图将其托管在控制台应用程序中。 I've worked through several tutorials but can't get it to work.
我已经完成了一些教程,但无法正常工作。
My guess is that it is a fairly simple mistake in the Program.cs since the same service works if it is hosted within IIS. 我的猜测是,在Program.cs中这是一个非常简单的错误,因为如果将同一服务托管在IIS中,则该服务将起作用。
If I try accessing http://localhost:8080/Products/ I get a webpage that says no endpoint found. 如果我尝试访问http:// localhost:8080 / Products /,则会得到一个网页,提示找不到端点。
Program.cs Program.cs中
Uri baseAddress = new Uri("http://localhost:8080/");
// Create the ServiceHost.
using (WebServiceHost host = new WebServiceHost(typeof(ProductRESTService), baseAddress))
{
host.Open();
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
// Close the ServiceHost.
host.Close();
}
IProductRestService.cs IProductRestService.cs
[ServiceContract]
public interface IProductRESTService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "http://localhost:8080/Products/")]
List<Product> getProductList();
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "http://localhost:8080/Product/{id}/")]
Product getProduct(string id);
}
ProductRestService.cs ProductRestService.cs
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class ProductRESTService : IProductRESTService
{
public Product getProduct(string id)
{
return Products.Instance.GetProduct(Convert.ToInt32(id));
}
public List<Product> getProductList()
{
return Products.Instance.ProductList;
}
}
The Product and Products classes are here http://pastebin.com/FRFxsWBU but I doubt that they are relevant. 产品和产品类在此处http://pastebin.com/FRFxsWBU,但我怀疑它们是否相关。
Thanks! 谢谢!
Ok, I found a solution myself. 好的,我自己找到了解决方案。 The mistake was really rather stupid: In the IProductRestService.cs the UriTemplates are supposed to be templates not URIs themselves.
这个错误确实非常愚蠢:在IProductRestService.cs中,UriTemplates应该是模板,而不是URI本身。
Now I have this: 现在我有这个:
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/Products/")]
List <Product> getProductList();
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/Product/{id}/")]
Product getProduct(string id);
And it works as expected. 它按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.