Pedro Félix's shared memory

ASP.NET Web API: Creating an Host using Azure Service Bus

In the last posts, I’ve presented the new ASP.NET Web API processing architecture and described three different hosting capabilities, supported “out of the box”: web hosting, in-memory hosting and self-hosting.

In this post, I will describe the development of a custom host using the Azure Service Bus relaying capabilities. This new host enables the exposure of a Web API on the public cloud, while running on a private machine (e.g. my laptop), that is, a machine without inbound connectivity (e.g. private addresses, firewall, NAT).

This host design is inspired in the self-host architecture, namely the usage of WCF and its integration with the service bus and WCF. Is composed by the following main components, shown in the following diagram.

 

 

 


    [ServiceContract]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    internal class DispatcherService
    {
        private readonly HttpServer _server;
        private readonly HttpServiceBusConfiguration _config;

        public DispatcherService(HttpServer server, HttpServiceBusConfiguration config)
        {
            _server = server;
            _config = config;
        }

        [WebGet(UriTemplate = "*")]
        [OperationContract(AsyncPattern = true)]
        public IAsyncResult BeginGet(AsyncCallback callback, object state)
        {
            var context = WebOperationContext.Current;
            return DispatchToHttpServer(context.IncomingRequest, null, 
				context.OutgoingResponse, _config.BufferRequestContent, callback, state);
        }

        public Message EndGet(IAsyncResult ar)
        {
            var t = ar as Task;
            var stream = t.Result;
            return StreamMessageHelper.CreateMessage(MessageVersion.None, "GETRESPONSE", stream ?? new MemoryStream());
        }

        [WebInvoke(UriTemplate = "*", Method = "*")]
        [OperationContract(AsyncPattern = true)]
        public IAsyncResult BeginInvoke(Stream s, AsyncCallback callback, object state)
        {
            var context = WebOperationContext.Current;
            return DispatchToHttpServer(context.IncomingRequest, s, 
				context.OutgoingResponse, _config.BufferRequestContent, callback, state);
        }

        public Message EndInvoke(IAsyncResult ar)
        {
            var t = ar as Task;
            var stream = t.Result;
            return StreamMessageHelper.CreateMessage(MessageVersion.None, "GETRESPONSE", stream ?? new MemoryStream());
        }
		...
    }

 

The code, still in alpha/”works in my machine” status, is available from https://github.com/pmhsfelix/WebApi.Explorations.ServiceBusRelayHost.

Feedback is appreciated.