I would like to create a service which returns a simple string. So far I have created a WCF REST Service using Template 40(CS) the following way:
Service class:
namespace MobileREST
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class UserService
{
[WebGet(UriTemplate = "IMSI={i}", ResponseFormat = WebMessageFormat.Json)]
public string GetUsername(string i)
{
string username = DBWorks.GetUserName(i);
return username;
}
}
}
Web.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
<connectionStrings>
<add name="LocalDBString" connectionString="Data Source=.\sqlexpress;Initial Catalog=MobileRestDB;Integrated Security=True"/>
<add name="SecurityConnString" connectionString="Data Source=.\sqlexpress;Initial Catalog=LopataDB;Integrated Security=True" />
</connectionStrings>
</configuration>
The solution works fine while debugging, but I haven’t found the way to host this service in windows (console) application or IIS in order to expose the service.
The client is supposed to create GET or POST requests and receive short answers. In debug mode the request to http://localhost:portNumber/UserService/IMSI=xxx returns just a string xxx (without http headers) which is perfect but I don’t know how to expose the same solution in order to host it at http://customWebAddress/UserService/IMSI=xxx and get the same result.
I would really appreciate if anyone could suggest any solution or provide any useful resource regarding the above problem.
To self-host this (in a console app or a NT Service), use something along the lines of this:
That creates an instance of the
WebServiceHostwhich is the service host descendant that knows how to handle REST services, and establishes a base address for your service to be called on.Once this app is running, you should be able to browse to
http://localhost:6677/UserServiceand see your service there…