RobVious
RobVious

Reputation: 12915

Accessing WebAPI endpoints with javascript from within the same Solution while hosted?

In the past I've built applications in two totally decoupled parts - the serverside WebAPI with endpoints, and the clientside web application. Two different solutions in visual studio. Then in my client's dataservice, I point all AJAX calls to wherever the API endpoints are hosted.

Right now I'm trying to build a single solution with both the clientside and serverside bits, and I'm wondering where my AJAX calls should point. I can use localhost when developing locally, but what about when it's hosted in something like Azure Websites?

tldr:

What endpoint should be specified in AJAX calls that live in the same solution as the WebAPI endpoints?

Upvotes: 0

Views: 192

Answers (1)

Olav Nybø
Olav Nybø

Reputation: 11568

If you are making AJAX calls from a browser back to the same server as the script was loaded from you can simply use a URL without specifying the host. It will be relative to the server and will work regardless of where your web-server is located.

Assuming your Web-API use the default path /api/controller and you are using JQuery then you could use this code to get a resource called myresource:

$.getJSON('/api/myresource', function (data) {
     //todo: write some code that use the returned data
    });

Upvotes: 2

Related Questions