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

← PrevNext →

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.

    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)
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.

← PreviousNext →