Klaus Nji
Klaus Nji

Reputation: 18847

JavaScript: cross site request on localhost on ASP.NET WebAPI

I have an ASP.NET WebAPI application running on

http://localhost:13057/worldwind 

I have another ASP.NET MVC5 application running on

http://localhost:2425/worldwind

When the client code on the MVC5 application attempts the following AJAX call:

 $.ajax(http://localhost:13057/worldwind/images, 
            {                
                type: "GET",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: Utilities.Logger.displayAjaxError,
                success: this.onImagesRetrieved,
                context: this               
            });

I get error:

XMLHttpRequest cannot load http://localhost:13057/worldwind/api/images. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:2425' is therefore not allowed access.

If I change the dataType in the AJAX request to jsonp, the WebAPI is being invoked even though I get error

jQuery18209344927002675831_1412452833242 was not called

How do I get this thing working?

Upvotes: 1

Views: 844

Answers (2)

Klaus Nji
Klaus Nji

Reputation: 18847

I ended up enabling CORS following instructions from here

This involved 3 steps (well, after fighting with other NuGet upgrade issues):

  1. Adding NuGet package Microsoft.AspNet.WebApi.Cors
  2. Adding the following lines in WebApiCconfig.Register static method:

        var cors = new EnableCorsAttribute("http://locahost:2425", "*", "*");
        config.EnableCors(cors);
    
  3. Rebuilding and running.

Upvotes: 2

Sing
Sing

Reputation: 4052

if your .jsp put in

http://localhost:13057/MySite/JSONP.jsp

use your script section like this:

<script type = "text/javascript" src="http://localhost:13057/MySite/JSONP.jsp?callback=jsonHandler"></script>

hope it will be help.

Upvotes: 0

Related Questions