ASP.net Examples

Download Java SE 8.

ASP.net Web API with Key based authentication

ASP.net REST Web API

Web API is used to implement CRUD operations ( create, read, update and delete ).

Steps to create asp.net web api with key based authentication

1) Create a new asp.net web application project.

asp.net web application project

2) Select Empty asp.net web application and choose MVC and Web API core references.

asp.net web api project

3) Create a folder 'MessageAPIHandler' and add class file for custom authorization handlaer as 'AuthorizationHandler.cs'.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace WebAPIKeyAuth.MessageAPIHandler
{
    public class AuthorizationHandler: DelegatingHandler
    {
        public const string APIKeyConfigured = "admin";

        protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable headerAPIkeyValues = null;
            if (request.Headers.TryGetValues("X-ApiKey", out headerAPIkeyValues))
            {
                var secretKey = headerAPIkeyValues.First();

                if (!string.IsNullOrEmpty(secretKey) && APIKeyConfigured.Equals(secretKey))
                {
                    return await base.SendAsync(request, cancellationToken);
                }
            }
            return request.CreateResponse(System.Net.HttpStatusCode.Forbidden, "API key is invalid.");
        }
    }
}

4) Add below code in Application_Start Event Handler of Global.asax.cs

GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthorizationHandler());

5) Create Employee domain class as file name 'Employee.cs'.

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Designation { get; set; }
    }

5) Create Controller as 'EmmployeeController.cs' with below code under Controller folder.

[FromBody] attribute is used to get the value of the Employee item from the body of the HTTP request.
HTTP GETmethod is indicated by the [HttpGet] attribute, and HTTP POST method is indicated by the [HttpPost] attribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebAPIKeyAuth.Controllers
{
    public class EmployeeController : ApiController
    {
        [HttpGet]
        [Route("api/employees")]
        public IHttpActionResult GetEmployees()
        {
            List employeeList = new List()
            {
                new Employee() {Id = 1, Name="Employee1", Designation="Manager" },
                 new Employee() {Id = 2, Name="Employee2", Designation="Supervisor" }
            };
            return Ok(employeeList);
        }
        [HttpPost]
        [Route("api/employee/add")]
        public IHttpActionResult AddEmployee([FromBody]Employee employee)
        {
            return Ok("Employee is added in the system, Employee: " + "ID: " + employee.Id.ToString() + ", Name: " + employee.Name);
        }
    }
}

Running Web API using Postman chrome web store

Running REST Web API is just like launching any asp.net web or press F5.

To test the Web API, Postman App is available in Chrome Web Store.

Get Request

Need to send X-ApiKey key and value in request header values.

postman get request

Post Request

Need to sendX-ApiKey key and value in request header values.

Need to sendId, Name, and Designation key's and value's in request body values.

postman post request header
postman post request body



Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^