Tuesday, May 12, 2015

Specify Routing in OWIN middleware

If you have used OWIN already then probably you know how OWIN sitss in middle of IIS and application and reduce dependency between them.

We know that we can plug component in OWIN middleware based on need. In this article we will implement Routing in OWIN middleware. So, in time of application start we will inject WebAPI route in OWIN middleware and application will use this.

Let’s take one MVC application and make sure OWIN is installed in application. I have used NuGet to install it. To inject OWIN in IIS you can execute this command in console.

Install-Package Microsoft.Owin.Host.SystemWeb

Here is definition of Startup.cs class where we injcted routing.

[assembly: OwinStartup(typeof(EFLearning.Startup))]
namespace EFLearning
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            //IDependencyResolver
            HttpConfiguration config = new HttpConfiguration();
           
            //set routing
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id =RouteParameter.Optional }
                );

            app.UseWebApi(config);

            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        }
    }
}

Now, make sure API routing is removed from your WbApiConfig.cs file , If this is present in application. Here is my simple controller.

public class HomeController : ApiController
    {
        public void Get()
        {

        }
    }


Let’s try to execute Get() .


No comments:

Post a Comment