barebones web server in WCF: no app.config needed

using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;
 
namespace StaticWebServer
{
    public class WebServerHost
    {
        public static void Main()
        {
            var host = new WebServiceHost(typeof(StaticContentService),new Uri("http://localhost:8000/"));
            host.AddServiceEndpoint(typeof(IStaticContentService), new WebHttpBinding(), "");
            host.AddServiceEndpoint(typeof(IFetcherService), 
                    new WebHttpBinding(){TransferMode = TransferMode.Streamed}, //to support large files like 70MB
                    "");
            host.Open();
            while (true) Console.ReadKey(true);
        }
    }
 
    [ServiceContract]
    public interface IStaticContentService
    {
        [OperationContract]
        Stream GetStaticContent(string content);
    }
 
    /// <summary>
    /// In total, exactly *2* files deployed to C:/temp --
    ///
    /// Since I copied my compiled EXE (#1) to C:/temp, I needed a dummy C:/temp/www/a.html (#2).
    /// My browser could then show http://localhost:8000/www/a.html 
    ///
    /// - no config file -- You can remove app.config completely.
    /// - no dll, 
    /// - no IIS, 
    /// - no windows service.
    ///
    /// This WCF service is hosted in a console host.
    /// </summary>
    class StaticContentService : IStaticContentService
    {
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/www/{*content}")]
        public Stream GetStaticContent(string content)
        {
            Console.WriteLine("GetStaticContent() " + content);
            var response = WebOperationContext.Current.OutgoingResponse;
            string path = "www/" + (string.IsNullOrEmpty(content) ? "a.html" : content);
            if (File.Exists(path))
            {
                response.ContentType = "text/html";
                response.StatusCode = System.Net.HttpStatusCode.OK;
                return File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            }
            response.StatusCode = System.Net.HttpStatusCode.NotFound;
            return null;
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s