Monday 6 June 2016

Create a sample web api application with self Hosting

In this article we are going to see how to create a sample web api and self host it for this first create a Console Application , then using Nuget package manager install the following one
  • Microsoft.AspNet.WebApi.SelfHost
Then Start to build the application, in our example we can take the Employees as sample.


Api Controller:
******************
    public class Employee
    {
        public string Name { setget; }

        public int Age { setget; }
       
    }

    public class EmployeeController:ApiController
    {
        private static readonly IEmployeeRepository emp = new EmployeeRepository();

        public IEnumerable<Employee> Get()
        {
            return emp.GetAllEmployee();
        }

        public Employee Get(string name)
        {
            return emp.GetAllEmployee().Where(x => x.Name == name).FirstOrDefault();
        }

        [ActionName("PostEmployee1")]
        [HttpPost]
        public int Emp(string name,int age)
        {
            emp.GetAllEmployee().Add(new Employee() {Name=name ,Age=age});
            return emp.GetAllEmployee().Count;
        }

        [ActionName("PostEmployee2")]
        [HttpPost]
        public int PostEmployee([FromBody]Employee empl)
        {
            emp.GetAllEmployee().Add(new Employee() { Name = empl.Name, Age = empl.Age });
            return emp.GetAllEmployee().Count;
        }

    }


Repository:

    interface IEmployeeRepository
    {
        List<Employee> GetAllEmployee();
    } 

    public class EmployeeRepository:IEmployeeRepository
    {
        List<Employee> employees = new List<Employee>() { new Employee()                                       {Name="Ram",Age=34},new Employee(){Name="Kumar",Age=30}};
        public List<Employee> GetAllEmployee()
        {
            return employees;
        }
    }


Assembly Resolver:
******************
    public class EmpAssemblyResolver:IAssembliesResolver
    {
        private string path;

        public EmpAssemblyResolver(string assempath)
        {
            this.path = assempath;
        }

        public ICollection<System.Reflection.Assembly> GetAssemblies()
        {
            List<Assembly> assemblies= new List<Assembly>();
            assemblies.Add(Assembly.LoadFrom(path));
            return assemblies;
        }
    }


Hosting :


Uri _baseaddress = new Uri("http://localhost:8070/");
            var assemloc = Assembly.GetExecutingAssembly().Location;
            string assempath = assemloc.Substring(0, assemloc.LastIndexOf("\\")) + @"\WebApiSamples.exe";
           
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseaddress);
            config.Services.Replace(typeof(IAssembliesResolver), new EmpAssemblyResolver(assempath));
            config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });

            using (HttpSelfHostServer hostserver = new HttpSelfHostServer(config))
            {
                Console.WriteLine("Waiting ....");
                hostserver.OpenAsync().Wait();

                GetEmployees();
                PostEmployeeinUrl();
                Console.WriteLine();
                Console.Read();
            }
           


Main Program:


    class Program
    {
        static void Main(string[] args)
        {
           
            Uri _baseaddress = new Uri("http://localhost:8070/");
            var assemloc = Assembly.GetExecutingAssembly().Location;
            string assempath = assemloc.Substring(0, assemloc.LastIndexOf("\\")) + @"\WebApiSamples.exe";
           
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseaddress);
            config.Services.Replace(typeof(IAssembliesResolver), new EmpAssemblyResolver(assempath));
            config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}",                       defaults: new { id = RouteParameter.Optional });

            using (HttpSelfHostServer hostserver = new HttpSelfHostServer(config))
            {
                Console.WriteLine("Waiting ....");
                hostserver.OpenAsync().Wait();

                GetEmployees();
                PostEmployeeinUrl();
                Console.WriteLine();
                Console.Read();
            }
           



        }

        private static async void GetEmployees()
        {
            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage res = await client.GetAsync(new                                                              Uri("http://localhost:8070/api/Employee/Get"));
                res.EnsureSuccessStatusCode();
                string successmess = await res.Content.ReadAsStringAsync();
                var empl = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Employee>>(successmess);

                Console.WriteLine("Employee Count "+ empl.Count);
                foreach (Employee e in empl)
                {
                    Console.WriteLine("Name "+e.Name+", Age : "+e.Age);
                }

            }
            catch (Exception ex)
            {

            }
        }

        private static async void PostEmployeeinUrl()
        {
            try
            {

                Console.WriteLine("");
                HttpClient client = new HttpClient();
                var postdat = new List<KeyValuePair<stringstring>>();
                postdat.Add(new KeyValuePair<stringstring>("name""sur"));
                postdat.Add(new KeyValuePair<stringstring>("age""23"));
                HttpContent content = new FormUrlEncodedContent(postdat);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                HttpResponseMessage res = await client.PostAsync(new     
                    Uri("http://localhost:8070/api/Employee/PostEmployee1"),content);
                res.EnsureSuccessStatusCode();
                var count = res.Content.ReadAsStringAsync();
                Console.WriteLine();
                Console.WriteLine("Adding a new employee");
                Console.WriteLine("Added succesfully ,EmployeeCount " + count.Result);
            }
            catch (Exception ex)
            {

            }
        }

        private static async void PostEmployee()
        {
            try
            {
               
                Console.WriteLine("");
                HttpClient client = new HttpClient();               
                MediaTypeFormatter formatter =  new JsonMediaTypeFormatter();
                HttpContent content = new ObjectContent<Employee>(new Employee()
                            {Name="r",Age=24},formatter,"application/json");
                HttpResponseMessage res = await client.PostAsync(new 
                           Uri("http://localhost:8070/api/Employee/PostEmployee2"), content);
                res.EnsureSuccessStatusCode();
                var count = res.Content.ReadAsStringAsync();
                Console.WriteLine();
                Console.WriteLine("Adding a new employee");
                Console.WriteLine("Added succesfully ,EmployeeCount "+count.Result);
            }
            catch (Exception ex)
            {

            }
        }

    }

Output:



When invoke from advance rest client 
url :
http://localhost:8070/api/Employee/PostEmployee1?name=rajesh&age=30

output:
3

From this article you can learn how to create the sample web Api and self host it.

No comments:

Post a Comment