Qadeer Mangrio Qadeer Mangrio - 3 months ago 47
JSON Question

Cross-Origin Request Blocked: & Reason: CORS header 'Access-Control-Allow-Origin' missing

perhaps this question seems duplicate, but I have my own scenario,

ASP.NET MVC
application, when I click on check-out it throws following error.


Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
http://gellio.telemosolutions.net/gellio/OsmosService.svc/OrderPlacement?order=%5Bobject%20Object%5D.
(Reason: CORS header 'Access-Control-Allow-Origin' missing).


enter image description here

here is JSON

theApp.onPageInit('CheckoutItems', function (page) {
var orderTotal = 0;
var totalItems = 0;
var orderId = 0;
var orderStatus = "Order can not be processed!";
if (basketItems != null && basketItems.length > 0) {
var orderData = [];

$.each(basketItems, function (index, value) {

var data = {
CoupanId: "1",
Discount: "1",
EmailAddress: "Areeb@hotmail.com",
ItemName: value.ItemName,
Item_Id: value.Item_Id,
Qty: value.Qty,
price: value.price,
};
orderData.push(data);
orderTotal += value.price;
});
totalItems = basketItems.length;
console.log(orderData);
$.ajax({
url: "http://osmos.telemosolutions.net/Osmos/OsmosService.svc/OrderPlacement/",
type: "Get",
dataType: "json",
contentType: "application/json;charset-uf8",
data: { order: orderData },
success: function (response) {
orderId = data;
if (data != null) {
orderStatus = "Order has been placed successfully.";
}
}

});


Web.Config




<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
</system.webServer>

Answer

You will not be able to access this service from javascript because you are on domain aaa.com and the service you are trying to access is on domain bbb.com.This is a security feature implemented by browsers called Same Origin Policy.

Specifying <add name="Access-Control-Allow-Origin" value="*"/> or enabling CORS from your side will not accomplish anything.You need to contact Telemo solutions and ask them to allow requests coming from your server\domain to call their service through javascript.This is ofcourse very unlikely to happen unless they are your business partner or you have some sort of agreement with them so what you will probably have to do is call their service methods from the C# code.

You can change your javascript to call a server side action\web method in your code behind and in the code behind write C# code to call the Telemo solutions methods:

Using a proxy to avoid same origin policy violations