AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Friday, 4 August 2017

How to create self-hosted Web API?

In this article I am going to discuss how to create a self hosting service in Web API. You can self-host a web API in your own host process. Please follow the below steps to create a self host API.

Step 1 - Create class library to add Api controllers

Step 2 - Install the Microsoft ASP.NET Web API library from nuget.
PM> Install-Package Microsoft.AspNet.WebApi

Step 3- Create a Test Controller file

public class TestController : ApiController
    {
        // GET api/test 
        public IEnumerable<string> Get()
        {
            return new string[] { "result1", "result2" };
        }

        // GET api/test/5 
        public string Get(int id)
        {
            return "test";
        }

        // POST api/test 
        public void Post([FromBody]string value)
        {

        }

        // PUT api/test/5 
        public void Put(int id, [FromBody]string value)
        {

        }

        // DELETE api/test/5 
        public void Delete(int id)
        {

        }
    }

Step 4- Add new Console application(SelfHost.Server)


Step 5- Install nuget package Microsoft ASP.NET web API self host in console application
PM> Install-Package Microsoft.AspNet.WebApi.SelfHost 

Step 6- Add following code in program.cs to create selfhost service
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.Http.SelfHost;

namespace SelfHost.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:5566");

            config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{id}",
             defaults: new { id = RouteParameter.Optional }
         );


            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                Type valuesControllerType = typeof(APIServiceLib.TestController);

                // Set our own assembly resolver where we add the assemblies we need
                //APIAssembliesResolver assemblyResolver = new APIAssembliesResolver();
                //config.Services.Replace(typeof(IAssembliesResolver), assemblyResolver);

                server.OpenAsync().Wait();                
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
    }

    public class APIAssembliesResolver : DefaultAssembliesResolver
    {
        public override ICollection<Assembly> GetAssemblies()
        {
            ICollection<Assembly> baseAssemblies = base.GetAssemblies();
            List<Assembly> assemblies = new List<Assembly>(baseAssemblies);
            var controllersAssembly = Assembly.LoadFrom(@"C:\somePath\controllerlib.dll");
            baseAssemblies.Add(controllersAssembly);
            return assemblies;
        }
    }
}

Here Port:5566 will be used to host the service. It requires an admin privileges to host the service so start visual studio to run as administrator. Hit URL http://localhost:5566/api/test you will get the result.
Source CodeDownload

0 comments :

Post a Comment

  • Popular Posts
  • Comments