I've just started working with WCF and tried creating a small REST HTTP service. If it is hosted in the IIS, it works fine. 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.
If I try accessing http://localhost:8080/Products/ I get a webpage that says no endpoint found.
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
[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
[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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.