简体   繁体   中英

Sending JSON from one asp.net web application to another

My solution contains two asp.net MVC projects. One is going to be a web-service, another a normal website, getting data from beforementioned web-service.

I have the following method in my web-service home controller:

...
public JSONResult GetTeacher(){
   return JSON(new {TeacherName = this.teacher.name });
}

I'm trying to access this method from the other web-application(which is going to be the website) by using this $.ajax method :

$.ajax({
    type: 'GET',
    url: 'localhost:11370/Home/GetTeacher',
    contentType: 'application/json; charset=utf-8',
    success: function (response) {
        alert(JSON.stringify(response));
        $('#results').html('Welcome, ' + response.Name);
    },
    error: function (error) {
        alert(JSON.stringify(error));
    }
});

When I start debugging my solution it opens up two web-development servers, both on different ports. As a result, when the $.ajax call happens I get a popup with this information:

the page at localhost:11510 says:
"readystate":0, "responsetext": "" , "status":0, "statustext":"error"

When I try running the script directly in the google chrome console I get the following message:

XMLHttpRequest cannot load http://localhost:11370/Home/GetTeacher. 
Origin http://localhost:11510 is not allowed by Access-Control-Allow-Origin.

Any help on how to actually access the method with $.ajax would be greatly appreciated.

Edit: I also tried making a simple html file to see what would happen if I would make the call to the web-service. Same result. Also, when I just type in the url to the method, it works fine and displays the name of the teacher.

Due to the same origin policy restriction that's built in browsers you cannot send cross domain AJAX requests. One possible workaround is to use CORS but since not all browsers support it yet, if you want a cross browser solution you may consider using JSONP .

You may take a look at this custom JsonpResult I wrote to illustrate how you could consume your controller action from a different domain. It is important to note that jQuery's JSONP implementation works only with GET requests. You cannot POST to a controller action cross domain. If you need to do that the only reliable way to achieve this would be to write a server side script on the home domain that will act as a bridge between the 2 domains. Then you would send the AJAX request to this new script that will delegate the request to the remote domain and return the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM