A web page cannot make calls to services (APIs) on a domain other than the one where the page came from. This is a security measure against a group of cross-site forgery attacks in which browsing to a bad site could potentially use the browser cookies to get data from a good site which the user had previously logged on (think your bank). There are many situations, however, where getting data from different sites is a perfectly valid scenario, such as mash-up applications which need data from different sources.
CORS (Cross-Origin Resource Sharing) is a new specification which defines a set of headers which can be exchanged between the client and the server which allow the server to relax the cross-domain restrictions for all HTTP verbs, not only GET. Also, since CORS is implemented in the same XmlHttpRequest as “normal” AJAX calls (in Firefox 3.5 and above, Safari 4 and above, Chrome 3 and above, IE 10 and above – in IE8/9, the code needs to use the XDomainRequest object instead), the JavaScript code doesn’t need to worry about “un-padding” responses or adding dummy functions. The error handling is also improved with CORS, since services can use the full range of the HTTP response codes (instead of 200, which is required by JSONP) and the code also has access to the full response instead of only its body.
Step-2:
Step-3:
using System;
Let's create a Web API IN ASP.NET WEB APPLICATION USING SCRIPT and latest version of the Entity Framework. And follow these below steps:
Step-1:
Step-1:
- Open Visual Studio, and select menu File > New > Project > Visual C# - Web > ASP.NET Web Application
- Set the project name WebApi and click OK.
- Select "WebApi" template,set "No Authentication", unchecked "Host in the cloud" options and click OK.
- After that, WebApi Solution will created.
Step-2:
Now Create Database "TestingDB" and Add table "dbo.TestEmployee" in Database
CREATE TABLE [dbo].[TestEmployee] (
[EmployeeId] INT IDENTITY (1, 1) NOT NULL,
[EmployeeName] VARCHAR (100) NULL,
[EmployeeAddress] VARCHAR (MAX) NULL,
[InsertedOn] DATETIME NULL,
[InsertedBy] INT NULL,
[IsActive] BIT NULL,
[IsDelete] BIT NULL,
CONSTRAINT [PK_TestEmployee] PRIMARY KEY CLUSTERED ([EmployeeId] ASC)
);
Step-3:
Add Entity "TestingDBEntities" in model directory.
Now add a Handler class "CorsHandler.cs". And Write these below code in "CorsHandler.cs".
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
namespace WebApi.Handlers
{
public class CorsHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew<HttpResponseMessage>(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
}
Step-5:
Now write this below coding in "Global.asax".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApi.Handlers;
namespace WebApi
{
public class WebApiApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.GetRegisteredBundles();
GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
}
}
}
Step-6:
Now add Controller "ValuesController.cs" in controller folder in this solution. Write these below code in "ValuesController.cs".
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Http.Cors;
using WebApi_Using_cors.Models;
namespace WebApi.Controllers
{
public class ValuesController : ApiController
{
// GET: api/values
TestingDBEntities ob = new TestingDBEntities();
public IEnumerable<TestEmployee> Get()
{
var data = (from a in ob.TestEmployees
where a.IsDelete==false
select a).ToList();
return data;
}
// GET: api/values/4
public IEnumerable<TestEmployee> Get(int id)
{
var data = (from a in ob.TestEmployees.ToList()
where a.EmployeeId == id
select a).ToList();
return data;
}
// POST: api/values
public HttpResponseMessage Post(Employee user)
{
try
{
TestEmployee apl = new TestEmployee();
apl.EmployeeName = user.EmployeeName;
apl.EmployeeAddress = user.EmployeeAddress;
apl.InsertedBy = 1;
apl.InsertedOn = DateTime.Now;
apl.IsActive = true;
apl.IsDelete = false;
ob.TestEmployees.Add(apl);
ob.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
// PUT: api/values/5
public HttpResponseMessage Put(Employee on)
{
try
{
TestEmployee apl = ob.TestEmployees.Where(a => a.EmployeeId == on.EmployeeId).FirstOrDefault();
apl.EmployeeName = on.EmployeeName;
apl.EmployeeAddress = on.EmployeeAddress;
ob.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
// DELETE: api/values/5
public HttpResponseMessage DELETE(int? id)
{
try
{
TestEmployee apl = ob.TestEmployees.Where(a => a.EmployeeId == id).FirstOrDefault();
apl.IsDelete = true;
ob.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
public partial class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string EmployeeAddress { get; set; }
public Nullable<System.DateTime> InsertedOn { get; set; }
public Nullable<int> InsertedBy { get; set; }
public Nullable<bool> IsActive { get; set; }
public Nullable<bool> IsDelete { get; set; }
public string Type { get; set; }
}
}
}
Step-7: Add new Asp.Net Web Application
Now create the another application "WebApi_Using_cors" in this solution :
- Right click on solution, and select menu add> New Project >.C# >Empty Web Application
- Provide the web site a name such as "WebApi_Using_cors" or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" - "Testing.aspx page".
- Drag and drop required controls on the <form> section of the Testing.aspx page.
Step-8:
In "Testing.aspx page" , Write this below code in Design Page...
In "Testing.aspx page" , Write this below code in Design Page...
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Testing.aspx.cs" Inherits="WebApi_Using_cors.Testing" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-3.1.1.js"></script>
<script src="Scripts/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function () {
var valuesAddress = "http://localhost:50895/api/values";
onloaddata();
function onloaddata() {
$.ajax({
url: valuesAddress,
type: "GET",
success: function (result) {
for (var i = 0; i < result.length; i++) {
$("#GridView1").append("<tr><td>" + result[i].EmployeeId + "</td><td>" + result[i].EmployeeName + "</td><td>" + result[i].EmployeeAddress + "</td></tr>");
}
},
error: function (jqXHR, textStatus, errorThrown) {
$("#result").text(textStatus);
}
});
}
$("#btnsave").click(function () {
var Employee = new Object();
Employee.EmployeeName = $("#txtname").val();
Employee.EmployeeAddress = $("#txtaddress").val();
$.ajax({
url: valuesAddress,
type: "POST",
data:Employee,
success: function (result) {
$("#txtname").val('');
$("#txtaddress").val('');
alert('Successfully Saved');
location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
$("#txtname").val('');
$("#txtaddress").val('');
alert('Successfully Saved');
}
});
})
$("#btnget").click(function () {
var id = $("#txtid").val();
$.ajax({
url: valuesAddress+'/'+id,
type: "GET",
data: '{"id":"'+id+'"}',
success: function (result) {
debugger;
$("#txtname").val(result[0].EmployeeName);
$("#txtaddress").val(result[0].EmployeeAddress);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error Occured');
}
});
})
$("#btndelete").click(function () {
var id = $("#txtid").val();
$.ajax({
url: valuesAddress + '/' + id,
type: "DELETE",
data: '{"id":"' + id + '"}',
success: function (result) {
debugger;
alert('Deleted Successfully');
location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error Occured');
}
});
})
$("#btnUpdate").click(function () {
debugger;
var id = $("#txtid").val();
var Employee = new Object();
Employee.EmployeeId = $("#txtid").val(),
Employee.EmployeeName = $("#txtname").val(),
Employee.EmployeeAddress = $("#txtaddress").val()
//Employee.Type == 'Update'
$.ajax({
url: valuesAddress + '/' + id,
type: "PUT",
data: Employee,
success: function (result) {
$("#txtname").val('');
$("#txtaddress").val('');
alert('Successfully Updated');
location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
$("#txtname").val('');
$("#txtaddress").val('');
alert('Successfully Saved');
}
});
})
});
</script>
</head>
<body>
<form id="form1" runat="server">
<p>Student Id: <asp:textbox ID="txtid" runat="server"></asp:textbox><input type="button" id="btnget" value="Search" /><input type="button" id="btndelete" value="Delete" /></p>
<p>Student Name: <asp:textbox ID="txtname" runat="server"></asp:textbox></p>
<p>Student Address: <asp:textbox ID="txtaddress" runat="server"></asp:textbox></p>
<p><input type="button" id="btnsave" value="Save" /><input type="button" id="btnUpdate" value="Update" /></p>
<div>
<asp:GridView ID="GridView1" runat="server" Width="1000px" ShowHeaderWhenEmpty="True" CellPadding="4" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellSpacing="2" ForeColor="Black">
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
</form>
</body>
</html>
Step-9:
In "Testing.aspx page" , Write this below code in "Testing.aspx.cs" Page...
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApi_Using_cors
{
public partial class Testing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("EmployeeId");
dt.Columns.Add("EmployeeName");
dt.Columns.Add("EmployeeAddress");
GridView1.DataSource = dt;
GridView1.DataBind();
txtaddress.Text = "";
txtid.Text = "";
txtname.Text = "";
}
}
}
}
0 Comments