开发者

Get application root from Request object that works locally and remotely

Let's say that I have my ASP.NET web application in a directory called "MyApp" both locally and on a remote server. I'm trying to build an onclick response to a link. The response calls a Javascript function, passing it the URL of an .aspx page in my web app. The Javascript pops out a new window displaying the page. My C# code looks like this:

link = new HyperLink();
link.Text = product_num_str;
link.NavigateUrl = "#";

string url = "Javascript:My_NewWindow('http://" + 
             HttpContext.Current.Request.Url.Authority +
             "/ProductInfo.aspx?_num=" + product_num_str + "')";

link.Attributes.Add("onclick", url);

I started using the Request's Authority property because I was having problems running locally on the Visual Studio web server when I used the Host property. The problem was that Host only returned "localhost" instead of the host and port number.

When tested locally, the code works because the "authority" maps to my app root folder. The URL generated is, e.g.,

http://localhost:52071/ProductInfo.aspx?_num=123

If I run on a remote server, however, I end up with something like:

http://company-server/ProductInfo.aspx?_num=123

This fails to find the page, because in this case the "MyApp" root folder must be included.

There is probably an easier way - putting an entry in the web.config开发者_StackOverflow中文版 or something. My motivation originally was to allow the app to be published to a folder of any name and work as is.

I could hack my approach and search the string for "localhost" or something, but that's ugly. So how do I build a string that will work everywhere?


I'm assuming you're doing this from within a Page or Control. If that's the case you should do this instead:

string fullUrl = this.ResolveClientUrl("~/ProductInfo.aspx?_num=" + product_num_str + ");

That will give you the proper URL no matter where the application is deployed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜