Hosting ASP.NET WEB API

You may want to host you HTTP Service i.e. ASP.NET WEB API in a console app. well it can be easily done.

to show this lets create a console app and add reference to the following assemblies:

System.Web
System.Web.Http
System.Web.Http.Common
System.Web.Http.SelfHost
System.Web.Http.WebHost
System.Net;
System.Net.Http.Formatting;
System.Net.Http.Headers;
 

this step is optional but for just touching on Json.net I am going to install Json.net using Nuget.

image

 

Now lets add a CarInfo class to return it in our controller

   1:      public class CarInfo
   2:      {
   3:          private readonly DateTime releaseDate = DateTime.UtcNow;
   4:          private readonly Dictionary<int, string> availableColors = new Dictionary<int, string>  
   5:            {         
   6:            { 1, "yellow"},   
   7:            { 2, "red" },   
   8:            { 3, "black" }, 
   9:            };
  10:   
  11:          public string Name
  12:          {
  13:              get
  14:              {
  15:                  return "BMW X6";
  16:              }
  17:          }
  18:          public DateTime ReleaseDate { get { return releaseDate; } }
  19:          public IDictionary<int, string> AvailableColors { get { return availableColors; } }
  20:      }

 

And let’s create our home controller as bellow:

 

   1:      public class HomeController : ApiController
   2:      {
   3:          // GET /api/<controller>
   4:          public CarInfo Get()
   5:          {
   6:              return new CarInfo();
   7:          }
   8:      }

as you see our controller has got just one method which responds to the Get request.

we also need a little helper class to integrate JSon.net to our application. please note as mentioned above using Json.net is optional.

 

  public class JsonNetFormatter : MediaTypeFormatter
    {
        private readonly JsonSerializerSettings jsonSerializerSettings;
 
        public JsonNetFormatter(JsonSerializerSettings jsonSerializerSettings)
        {
            this.jsonSerializerSettings = jsonSerializerSettings ?? new JsonSerializerSettings();
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            Encoding = new UTF8Encoding(false, true);
        }
 
        protected override bool CanReadType(Type type)
        {
            return type != typeof(IKeyValueModel);
        }
 
        protected override bool CanWriteType(Type type)
        {
            return true;
        }
 
        protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, 
HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            var serializer = JsonSerializer.Create(this.jsonSerializerSettings);
 
            return Task.Factory.StartNew(() =>
            {
                using (var streamReader = new StreamReader(stream, Encoding))
                {
                    using (var jsonTextReader = new JsonTextReader(streamReader))
                    {
                        return serializer.Deserialize(jsonTextReader, type);
                    }
                }
            });
        }
 
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, 
HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        {
            var serializer = JsonSerializer.Create(this.jsonSerializerSettings);
 
            return Task.Factory.StartNew(() =>
            {
                using (var jsonTextWriter = 
new JsonTextWriter(new StreamWriter(stream, Encoding)) { CloseOutput = false })
                {
                    serializer.Serialize(jsonTextWriter, value);
                    jsonTextWriter.Flush();
                }
            });
        }
    }

ok it’s time to create actual host to host our service. you just need to add few lines of code to the main method of the program

        static void Main(string[] args)
        {
            // Set up server configuration    
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost:8081");
            config.Routes.MapHttpRoute("Default", "{controller}", new { controller = "Home" });
 
           
            JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
            serializerSettings.Converters.Add(new IsoDateTimeConverter());
            config.Formatters[0] = new JsonNetFormatter(serializerSettings);
 
            // Create server   
            var server = new HttpSelfHostServer(config);
 
            // Start listening   
            server.OpenAsync().Wait();
            Console.ReadLine();
        }

to test the application open Fiddler and create a request as below:

image

basically you need to set the address to http://localhost:8081/Home and content-type to Content-Type: application/json; charset=utf-8. once you create the request click on execute and you should be getting the following response back

image

as you see we get Json representation of the CarInfo object.

it was quit simple, wasn’t it?

Written by vahid

Sunday, March 18, 2012 at 4:26 AM

Tagged with ,

Leave a Reply