1) Create a new asp.net web application project.
2) Select Empty asp.net web application and choose MVC and Web API core references.
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 TaskSendAsync(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.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() { ListemployeeList = 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 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.
Need to send X-ApiKey key and value in request header values.
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.
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page