Web API IIS Hosting Using CORS With Angular JS
18:48Introduction
In this article I want to show how to use Web API 2 CORS (Cross Origin Resource Sharing) service with AngularJs.View Image
Table
CREATE TABLE Employee( [Id] [int] primary key IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NOT NULL, [Address] [nvarchar](500) NOT NULL, [Country] [nvarchar](50) NOT NULL, [City] [nvarchar](50) NOT NULL, [Mobile] [nvarchar](10) NOT NULL )
Stored Procedure
CREATE PROCEDURE sp_InsUpdDelEmployee @id int, @name nvarchar(50), @address nvarchar(500), @country nvarchar(50), @city nvarchar(50), @mobile nvarchar(50), @type varchar(10) AS Begin if(@type = 'Ins') Begin insert into Employee values(@name,@address,@country,@city,@mobile) End else if(@type = 'Upd') Begin update Employee set Name = @name, [Address] = @address, Country = @country, City = @city, Mobile = @mobile where Id = @id End else if(@type = 'Del') Begin delete from Employee where Id = @id End else if(@type = 'GetById') Begin select * from Employee where Id = @id End select * from Employee End
Service
Step By Step To Create Web API 2 Services
Enable CORS
There have 3 part to enabling CORS.
1. Origins: Specifies the URL from which we want to get cross-domain requests. We can add multiple values in a comma-separated format.
2. Headers: Specifies that author request headers are allowed.
3. Methods: Specifies the type of request, in other words GET, POST, PUT, DELETE, OPTIONS, that should be enabled on this method.
var cors = new EnableCorsAttribute([Origins], [Headers], [Methods]); config.EnableCors(cors);
I enable CORS in the WebApiConfig like this:
var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors);
If you use the value "*" that means it allow all the Origins, Headers or Methods
Test API Controller
using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Web_API_IIS_Hosting_Services.Models; using System.Web.Http.Cors; using System.Web.Cors; using System.Threading.Tasks; using System.Threading; using System.Net.Http.Headers; namespace Web_API_IIS_Hosting_Services.Controllers { public class TestAPIController : ApiController { // Get All The Employee public ListWebApiConfig.csGet() { List emplist = new List (); using (dbEntities db = new dbEntities()) { var results = db.sp_InsUpdDelEmployee(0, "", "", "", "", "", "Get").ToList(); foreach (var result in results) { var employee = new Employee() { Id = result.Id, Name = result.Name, Address = result.Address, Country = result.Country, City = result.City, Mobile = result.Mobile }; emplist.Add(employee); } return emplist; } } // Get Employee By Id public Employee Get(int id) { using (dbEntities db = new dbEntities()) { Employee employee = db.Employees.Find(id); if (employee == null) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); } return employee; } } // Insert Employee public HttpResponseMessage Post(Employee employee) { if (ModelState.IsValid) { using (dbEntities db = new dbEntities()) { var emplist = db.sp_InsUpdDelEmployee(0, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Ins").ToList(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, emplist); return response; } } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } } // Update Employee public HttpResponseMessage Put(Employee employee) { List emplist = new List (); HttpResponseMessage response = null; if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } using (dbEntities db = new dbEntities()) { try { emplist = db.sp_InsUpdDelEmployee(employee.Id, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Upd").ToList(); response = Request.CreateResponse(HttpStatusCode.OK, emplist); return response; } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } // Delete employee By Id public HttpResponseMessage Delete(int id) { List emplist = new List (); HttpResponseMessage response = null; using (dbEntities db = new dbEntities()) { var results = db.sp_InsUpdDelEmployee(id, "", "", "", "", "", "GetById").ToList(); if (results.Count == 0) { return Request.CreateResponse(HttpStatusCode.NotFound); } try { emplist = db.sp_InsUpdDelEmployee(id, "", "", "", "", "", "Del").ToList(); response = Request.CreateResponse(HttpStatusCode.OK, emplist); return response; } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } public HttpResponseMessage Options() { var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.OK; return response; } // Prevent Memory Leak protected override void Dispose(bool disposing) { using (dbEntities db = new dbEntities()) db.Dispose(); base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using System.Web.Http.Cors; namespace Web_API_IIS_Hosting_Services { public static class WebApiConfig { public static void Register(HttpConfiguration config) { var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }Add the following code in Web.config
<system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer>
Client
Step By Step To Create Client Application
Add NuGet Package
BundleConfig.cs
using System.Web; using System.Web.Optimization; namespace Web_API_IIS_Hosting_Client { public class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/js").Include( "~/js/angular.js", "~/js/app.js")); bundles.Add(new StyleBundle("~/css").Include( "~/css/bootstrap.css")); } } }app.js
var app = angular.module('myApp', []); app.controller('employeeController', ['$scope', '$http', employeeController]); app.config(['$httpProvider', function ($httpProvider) { // When accessing a web service using the $http object, automatically adds a X-Requested-With:XMLHttpRequest header to the request. To Eleminate this problem we use it. delete $httpProvider.defaults.headers.put['X-Requested-With']; // POST $httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; $httpProvider.defaults.headers.post['Access-Control-Max-Age'] = '1728000'; // PUT $httpProvider.defaults.headers.put['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded'; $httpProvider.defaults.headers.put['Access-Control-Max-Age'] = '1728000'; // COMMON $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.common['Content-Type'] = 'application/json'; $httpProvider.defaults.headers.common['Access-Control-Max-Age'] = '1728000'; $httpProvider.defaults.useXDomain = true; // Override $http service's default transformRequest $httpProvider.defaults.transformRequest = [function (data) { var param = function (obj) { var query = ''; var name, value, fullSubName, subName, subValue, innerObj, i; for (name in obj) { value = obj[name]; if (value instanceof Array) { for (i = 0; i < value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value instanceof Object) { for (subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value !== undefined && value !== null) { query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; } } return query.length ? query.substr(0, query.length - 1) : query; }; return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; }]; }]); // Execute app.run(['$q', '$rootScope', function ($q, $rootScope) {}]); // Angularjs Controller function employeeController($scope, $http) { // Declare variable $scope.loading = true; $scope.updateShow = false; $scope.addShow = true; var baseUrl = 'http://localhost:9877/api/TestAPI'; // IIS Hosting URL // var baseUrl = 'http://localhost:9878/api/TestAPI'; // Normal Service URL // Get All Employee $http.get(baseUrl).success(function (data) { $scope.employees = data; }).error(function () { $scope.error = "An Error has occured while loading posts!"; }); //Insert Employee $scope.add = function () { $scope.loading = true; $http.post(baseUrl + '/Post', this.newemployee).success(function (data) { $scope.employees = data; $scope.updateShow = false; $scope.addShow = true; $scope.newemployee = ''; }).error(function (data) { $scope.error = "An Error has occured while Adding employee! " + data; }); } //Edit Employee $scope.edit = function () { var Id = this.employee.Id; $http.get(baseUrl + '/' + Id).success(function (data) { $scope.newemployee = data; $scope.updateShow = true; $scope.addShow = false; }).error(function () { $scope.error = "An Error has occured while loading posts!"; }); } // Update Employee $scope.update = function () { $scope.loading = true; $http.put(baseUrl + '/Put', this.newemployee).success(function (data) { $scope.employees = data; $scope.updateShow = false; $scope.addShow = true; $scope.newemployee = ''; }).error(function (data) { $scope.error = "An Error has occured while Saving employee! " + data; }); } //Delete Employee $scope.delete = function () { if (confirm("Sure to delete?")) { var Id = this.employee.Id; $scope.loading = true; $http.delete(baseUrl + '/' + Id).success(function (data) { $scope.employees = data; }).error(function (data) { $scope.error = "An Error has occured while Saving employee! " + data; }); } } //Cancel Employee $scope.cancel = function () { $scope.updateShow = false; $scope.addShow = true; $scope.newemployee = ''; } }View
@Scripts.Render("~/js") @Styles.Render("~/css") <html ng-app="myApp"> <head><title>AngularJs With WebApi and Stored Procedure</title></head> <body> <div ng-controller="employeeController" class="container"> <div class="row"> <div class="col-md-12"> <h3 class="header">AngularJs With WebApi CORS and Stored Procedure</h3> </div> </div> <div class="row"> <div class="col-md-12"> <strong class="error">{{error}}</strong> <form name="addemployee" style="width: 600px; margin: 0px auto;"> <div class="form-group"> <label for="cname" class="col-sm-2 control-label">Name:</label> <div class="col-sm-10 space"> <input type="text" class="form-control" id="cname" placeholder="please enter your name" ng-model="newemployee.Name" required /> </div> </div> <div class="form-group"> <label for="address" class="col-sm-2 control-label">Address:</label> <div class="col-sm-10 space"> <textarea class="form-control" id="address" placeholder="please enter your address" ng-model="newemployee.Address" required></textarea> </div> </div> <div class="form-group"> <label for="country" class="col-sm-2 control-label">Country:</label> <div class="col-sm-10 space"> <input type="text" class="form-control" id="country" placeholder="please enter your country" ng-model="newemployee.Country" required /> </div> </div> <div class="form-group"> <label for="city" class="col-sm-2 control-label">City:</label> <div class="col-sm-10 space"> <input type="text" class="form-control" id="city" placeholder="please enter your city" ng-model="newemployee.City" required /> </div> </div> <div class="form-group"> <label for="mobile" class="col-sm-2 control-label">Mobile:</label> <div class="col-sm-10 space"> <input type="text" class="form-control" id="mobile" placeholder="please enter your mobile" ng-model="newemployee.Mobile" required /> </div> </div> <br /> <div class="form-group space"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" value="Add" ng-click="add()" ng-show="addShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" /> <input type="submit" value="Update" ng-click="update()" ng-show="updateShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" /> <input type="button" value="Cancel" ng-click="cancel()" class="btn btn-primary" /> </div> </div> <br /> </form> </div> </div> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-bordered table-hover" style="width: 800px; margin-left: 170px;"> <tr> <th>Name</th> <th>Address</th> <th>Country</th> <th>City</th> <th>Mobile</th> <th>Actions</th> </tr> <tr ng-repeat="employee in employees"> <td> <p>{{ employee.Name }}</p> </td> <td> <p>{{ employee.Address }}</p> </td> <td> <p>{{ employee.Country }}</p> </td> <td> <p>{{ employee.City }}</p> </td> <td> <p>{{ employee.Mobile }}</p> </td> <td> <p><a ng-click="edit()" href="javascript:void(0);">Edit</a> | <a ng-click="delete()" href="javascript:void(0);">Delete</a></p> </td> </tr> </table> </div> </div> </div> </div> </body> </html>Controller
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web; using System.Web.Mvc; namespace Web_API_IIS_Hosting_Client.Controllers { public class TestController : Controller { public ActionResult Index() { return View(); } } }
Step To Hosting In IIS
Windows + R --> Type Command "inetmgr" --> Enter --> IIS --> Right Click On Sites
Download
You can download Service application zip file hereYou can download Client application zip file here
0 comments