Cross Origin Resource Sharing using “Access-Control-Allow-Origin” in MVC 4

Hi,

In the below post we will learn that how we can use the “Access-Control-Allow-Origin” header information for CORS.

The w3c specification describes  talks about the “Access-Control-Allow-Origin” which can be used for cross domain request and responses.

http://www.w3.org/TR/cors/#http-access-control-allow-origin

Lets see how we can use it in MVC 4 framework. If you want to set the CORS for a particular request then you can set it using below method .

HttpContext.Response.AppendHeader(“Access-Control-Allow-Origin”,”*”);

Instead of passing “*” which means that CORS is enabled for all domain you can specify domain names on which you want CORS enabled . another way it to add it in web.config file .

image

below is the code of method which sends the json data back to the calling client. The JsonRequestBehavior ensure the permission to sends the json request.  so, I am setting it to AllowGet.

public JsonResult GetAllCustomers()
{
db.Configuration.ProxyCreationEnabled = false;
var customerList = db.Customers.ToList();
return Json(customerList, JsonRequestBehavior.AllowGet);

}

below is the cshtml page code which is from another domain and sending the Cross domain request . if does not request cshtml page you are free to use html.

@{
ViewBag.Title = "Customer List";
}

Index



@section scripts {

<script type="text/javascript">
function showCustomerList(data) {
var customerTable;
if (data) {
customerTable = "";
customerTable += ""
for (var i = 0; i < data.length; i++) {
customerTable += "";
customerTable += "";
customerTable += "";
customerTable += "";
customerTable += "";
}
customerTable += "
Customer IDCompany NameContact Name
" + data[i]["CustomerID"] + "" + data[i]["CompanyName"] + "" + data[i]["ContactName"] + "
"
;
}

$($.find("#customerList")).append(customerTable);
}

function LoadCustomerList() {
$.ajax({
type: 'GET',
url: "http://localhost:49416/Customer/GetAllCustomers",
async: false,
dataType: 'json',
success: function (data) {
showCustomerList(data);
},
error: function (e) {
console.log(e.message);
}
});
}
LoadCustomerList();

}

<div id="customerList">

In the above code the “LoadCustomerList” is sending ajax request and then after receiving response it is passing data back to “showCustomerList” method which is further processing it and displaying it .

 

after running I got the below window. remember server project should also be running.

image

In the network tab in chrome you can see what server is sending back.

image

You can see that in the response header server sets the “Access-Control-Allow-Origin” to “*”.

Hope you find this post useful, thanks for reading.

Advertisements