0

When using http in Angular the url must be specified in the JavaScript. I don't want to hard code the full url (e.g. http://www.example.com/Controller/GetDetails/) because this would mean code changes between live and test environments.

I've read examples that just use the relative path (e.g. /Contoller/GetDetails), however due to the way MVC routing works this often fails to work. As a simple example the home page can be accessed via:

  1. http://www.example.com
  2. http://www.example.com/home/
  3. http://www.example.com/home/index

and so adding the relative path isn't ideal because two out of three of these routes will get the wrong http url.

I thought initially that I could determine the base url from JavaScript and use:

window.location.protocol+"//"+window.location.host + "/Contoller/GetDetails"

But I have found that this fails if the MVC application is running in a folder and won't correctly resolve a url like:

http://www.example.com/MyApplication/Controller/GetDetails

I also considered using a more RESTful approach and handing all the urls needed for the JavaScript down as part of the json data - but of course, this leads to the chicken and egg situation of: If the http urls are provided in the json, how do I get the first json call to work?

What is a robust way of getting urls for use in AngularJS http calls to mvc.net?

Kaine
  • 1,285
  • 2
  • 16
  • 30

2 Answers2

1

If you're working with angular - you need to take a look at window service - $window and location service - $location. Using these you will easily resolve relative path issues. In addition - what you're calling MVC app folder - is app context.

fed.pavlo
  • 251
  • 1
  • 9
0

One way to do this seems to be to set up a JavaScript variable in the Layout page using .net code as seen in here:

How to get base URL of an MVC application using javascript

window.applicationBaseUrl = @Html.Raw(HttpUtility.JavaScriptStringEncode(
    new Uri(
               new Uri(this.Context.Request.Url.GetLeftPart(UriPartial.Authority)),
               Url.Content("~/")
           ).ToString(), true));

This allows you to call the http using the applicationBaseUrl

 $http({
                method: 'GET', url: window.applicationBaseUrl + '/Controller/GetDetails'
            })
Community
  • 1
  • 1
Kaine
  • 1,285
  • 2
  • 16
  • 30
  • 1
    Good except you should replace window.applicationBaseUrl with an Angular constant for dependency injection and testability: `yourApp.constant('applicationBaseUrl', @Html.Raw(HttpUtility.JavaScriptStringEncode(Url.Content("~/"), true)));` – mono68 Feb 24 '16 at 07:57