Imagine that you have a requirement to have a web API that supports hosting in both IIS and a windows service (an example of self hosting).
If you use OWIN and ASP.NET then it is not very difficult. In fact if you build one application using OWIN, you can host it in multiple ways. We will try IIS-Express and Console App. Let us start.
1. Create a new Web Application. Choose Empty template.
2. Use nuget package "Microsoft.Owin.Host.SystemWeb" and "Microsoft.AspNet.WebApi.Owin".
3. Use "OWIN Startup" class.
5. Add a test controller e.g. ValuesController like following.
5. Test the url.
Now that web application is up, let us see how easily we can host the same application in an Console application and not duplicate the code.
1. Add a console application. Add reference of the web application in console application.
2. Add nuget package "Microsoft.AspNet.WebApi.OwinSelfHost".
3. Change Program.cs to following.
static void Main(string[] args)
{
using (var x = WebApp.Start(url: "http://locahost:9000/"))
{
Console.WriteLine("Started");
Console.ReadLine();
}
}
4. Launch console app and access "http://localhost:9000/api/values".
Have fun.
If you use OWIN and ASP.NET then it is not very difficult. In fact if you build one application using OWIN, you can host it in multiple ways. We will try IIS-Express and Console App. Let us start.
1. Create a new Web Application. Choose Empty template.
2. Use nuget package "Microsoft.Owin.Host.SystemWeb" and "Microsoft.AspNet.WebApi.Owin".
3. Use "OWIN Startup" class.
4. Change Startup.cs.
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
app.UseWebApi(config);
}
}
5. Add a test controller e.g. ValuesController like following.
5. Test the url.
Now that web application is up, let us see how easily we can host the same application in an Console application and not duplicate the code.
1. Add a console application. Add reference of the web application in console application.
2. Add nuget package "Microsoft.AspNet.WebApi.OwinSelfHost".
3. Change Program.cs to following.
static void Main(string[] args)
{
using (var x = WebApp.Start
{
Console.WriteLine("Started");
Console.ReadLine();
}
}
4. Launch console app and access "http://localhost:9000/api/values".
Have fun.
No comments:
Post a Comment