Pregunta

I've a website created using ASP.NET MVC 5. Inside this website I've a "small SPA" created using AngularJS. To get/post data I use Web API (Default routing). I host my website using a sub-folder, so my URL looks like www.mydomain.com/MyApp.Web/ . When I try to create a URL for the resource service, I use a string like "/api/controllerName", but when angular gets/post to the server, it omits the sub-folder (MyApp.Web) in the URL, so actually it gets/posts to the URL like www.mydomain.com/api/controllerName. How can I make angular include sub-folder in the URL ?

¿Fue útil?

Solución 2

How can I make angular include sub-folder in the URL ?

By never hardcoding the url in your application but using a server side url helper to generate it:

<script type="text/javascript">
    var url = '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "controllerName" })';
    $.post(url, { foo: 'bar' }, function(result) {
        ...
    });
</script>

Alternatively you could use this helper in order to embed the correct url in some DOM element of your SPA. Suppose that you are AJAXifying an anchor. You would simply generate the proper url on the server:

<a href="@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "controllerName" })" id="mylink">Click me</a>

and then in your separate js file:

$('#mylink').click(function() {
    $.post(this.href, { foo: 'bar' }, function(result) {
        ...
    });
    return false;
});

Notice how an url is never hardcoded anywhere. It is guaranteed to be correct because it is generated by a server side url helper taking into account your routes configuration and any possible virtual directories.

Otros consejos

Similar to Darin's answer... Declare global variable in your index.html file:

<script>
    var rootUrl = '@Url.Content("~/")';
</script>

And then create a service which will be a wrapper of the standard $http. This wrapper when used then can check if url passed starts with "~" for example (as you are familiar with that from .NET) and, it construct the full url by combining the url passed and the rootUrl.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top