Self hosting console application

I wanted to create a self hosting console application without going to the hassle  of creating a new web application project. So all i had to do was to create a console application and then do the nuget and OWIN do the rest.

Create a new console project and paste this code in the main procedure.

 

static void Main(string[] args)
		{
			string baseAddress = "http://localhost:9000/";
 
			// Start OWIN host 
			using (WebApp.Start<Startup>(url: baseAddress))
			{
				// Create HttpCient and make a request to api/values 
				HttpClient client = new HttpClient();
 
				var response = client.GetAsync(baseAddress + "api/values").Result;
 
				Console.WriteLine(response);
				Console.WriteLine(response.Content.ReadAsStringAsync().Result);
				Console.ReadLine();
			}
		}

So the first thing that you will see if that you will get error as it is unable to identify the WebApp class. So the first thing that you need to do is to include the nuget package. Include the nuget package called ‘Microsoft.AspNet.WebApi.OwinSelfHost’ to the project and then try to compile and run the project. After that you will still get more error that Startup class is missing. So include this class.

public class Startup
	{
	    public void Configuration(IAppBuilder appBuilder)
		{
			// Configure Web API for self-host. 
			HttpConfiguration config = new HttpConfiguration();
			config.Routes.MapHttpRoute(
				 "DefaultApi",
				"api/{controller}/{id}"
			);
 
			appBuilder.UseWebApi(config);
		}
	}

Now compile the project and you will be able to compile. Lets see the code now

The WebApp.Start is taking a class called Statup as configuration. The configuration defines multiple configuartion paramatere  but here we are only defining the route though which the we will access the REST full API. Now when you run the application you will see a 404 as its still unable to find the values controller. So lets include that.

Snippet

public class ValuesController : ApiController
	{
		// GET api/values 
		public IEnumerable<string> Get()
		{
			return new string[] { "value1", "value2" };
		}
        }

Now run the app and you will see an output. Wohoo a successful self hosting app.