Bob Horn
Bob Horn

Reputation: 34335

URL path changes between dev and published version

I just got Scott Hanselman's chat app with SignalR working with ASP.NET MVC 4. After hours of configuration, trial and error, and getting different versions of Windows to talk to each other on my home network, it's all working except that I'm left with one issue that I'm not sure how to handle.

This line of javascript has to change, depending on if I'm running the app through Visual Studio or the published (IIS) version:

Works when running within VS:

var connection = $.connection('echo');

Works with published version:

var connection = $.connection('ChatWithSignalR/echo');

When I run within VS, the URL is:

http://localhost:9145/

And the published version is:

http://localhost/ChatWithSignalR

If I don't change that line of code, and try to run the app within VS, using the javascript that has ChatWithSignalR in it, I get an error like this:

Failed to load resource: the server responded with a status of 404 (Not Found)

http://localhost:9145/ChatWithSignalR/echo/negotiate?_=1347809290826

What can I do so that I can use the same javascript code and have it work in both scenarios?

var connection = $.connection('??????');

Note, this is in my Global.asax.cs:

RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}");

Upvotes: 0

Views: 283

Answers (1)

Ian
Ian

Reputation: 50933

This is something you need to take care of because the SignalR library has no idea where the app is deployed to and what its root address is. Something I always do in web applications is have a global Javascript variable called site_root and set it equal to the absolute URL for the root of the site. Now, to do this, you need server tags to evaluate and print that, something like "<%= RootUrl %>" or whatever the syntax is for your server language. Then, when referencing URLs in Javascript, you should always use site_root + "/echo" (with or without the beginning "/" depending on what's printed by the server variable/method). So you'd have something like:

<script type="text/javascript">
    var site_root = "<%= RootUrl %>";

    // Later, wherever in your code:
    function doSomething() {
        var echo_url = site_root + "/echo";
        // Now you have an absolute URL for the echo page
    }
</script>

Now, I put this in the master layout page that always is included - like a Master Page, or depending on what server language you use. Also, instead of a variable like RootUrl, you might use some method to resolve URLs, and just pass it an empty string or "/" to get the root URL for the application.

Upvotes: 1

Related Questions