Error: No ‘Access-Control-Allow-Origin’ Header is Present – Origin ‘localhost:…’ is therefore not allowed access

Recently I came across a situation where I was making a simple Ajax call using the “Get” method and few data, to an Asp.Net Web API controller service on the server. However, to my surprise I received an error saying, “No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:28146' is therefore not allowed access”.

XMLHttpRequest cannot load https://localhost:38331/api/books/.... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:28146' is therefore not allowed access.

I am sure you might have come across a similar situation. You can share it with us here. The JQuery Ajax properties that I have written looked like this.

$.ajax({
    type: 'GET',
    url: 'https://localhost:38331/api/books/',
    data: { iBookID: bookID,
        iUserRating: userRating
    },
    dataType: 'json',
    success: function (data) {
    }
});

It looks very simple and I have written and executed this method many times before in various other applications. However, this time I was stuck. Look carefully at the error that I have shared above, you will see that the service I am calling and the application that makes the Ajax call, runs on different ports.

The Web API service: “https://localhost:38331/api/books/”
The application: “https://localhost:28146”

The solution

You have to configure the service header (API Service) to respond to such a request (Ajax). You can add an https Response Header to respond to an Ajax request send from any website. All you have to do it add the below code in the Global.asax file in the server (the location where you have the service running).

Global.asax (C#)
protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin","*");
}
Vb.Net
Protected Sub Application_BeginRequest(sender As Object, e As EventArgs)
       HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*")
End Sub

Remember: Update the Global.asax file that resides in the server application, where you have created your Web API service. Therefore, you must have access to the service that is running at the server, to make the necessary changes.

Previous - Bind an SQL Server Stored Procedure with an Asp.Net SqlDataSourceNext - How to Send Emails in Asp.Net using Hotmail SMTP Mail Server



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts: