I need to develop a windows service that will do some basic task a few times a day, nothing heavy. As part of the requirements it needs a web interface so it can be configured from a browser.
Example:
Mr Engineer opens up his browser and enters
localhost:1234/Config
. A simple html web page is returned that allows him to enter some values and post them to the server. The windows service will then use these new values.
What I currently have is two different ways of doing this. The first is just by creating a WebServiceHost in my ServiceBase like so:
// Provide the base address.
serviceHost = new WebServiceHost(typeof(Service), new Uri(baseAddress));
// Open the ServiceHostBase
serviceHost.Open();
I then create an IService and specify an operation like so:
[OperationContract]
[WebGet]
Stream Get();
And finally implement the interface like so:
public Stream Get()
{
UriTemplateMatch uriInfo = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
MemoryStream rawResponse = new MemoryStream();
TextWriter response = new StreamWriter(rawResponse, Encoding.UTF8);
response.Write("<h1>test</h1>");
response.Flush();
rawResponse.Position = 0;
return rawResponse;
}
This works FINE. I am able to query the web service from my browser and I get the desired result.
However, I have recently stumbled across WebApi and have been able to replicate equal success by doing the following:
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(new Uri("http://localhost:50231/"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
// Create server
var server = new HttpSelfHostServer(config);
// Start listening
server.OpenAsync().Wait();
And then by having a controller like so:
public class HelloController : ApiController
{
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
response.Content = new StringContent("<html><body>Hello World</body></html>");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
}
So, these are the two methods I've come up with to meet the requirements. Which of these is considered better? Or are they both terrible and is there a better way?