6

I'm following a tutorial on this link http://www.codeproject.com/KB/aspnet/ASPNETService.aspx

Now I'm stuck at these codes

private const string DummyPageUrl = 
    "http://localhost/TestCacheTimeout/WebForm1.aspx";

private void HitPage()
{
    WebClient client = new WebClient();
    client.DownloadData(DummyPageUrl);
}

My local application address has a port number after "localhost", so how can I get the full path (can it be done in Application_Start method)? I want it to be very generic so that it can work in any cases.

Thanks a lot!

UPDATE

I tried this in the Application_Start and it runs fine, but return error right away when published to IIS7

String path = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/");
Leo
  • 2,173
  • 6
  • 28
  • 37

3 Answers3

7

If it is calling back to the same server, perhaps use the Request object:

var url = new Uri(Request.Url, "/TestCacheTimeout/WebForm1.aspx").AbsoluteUri;

Otherwise, store the other server's details in a config file or the database, and just give it the right value.

But a better question would be: why would you talk via http to yourself? Why not just call a class method? Personally I'd be using an external scheduled job to do this.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    All I'm trying to do is following the instructions from that site to simulate a service that can keep running and doing some stuffs for me over time. – Leo Nov 12 '10 at 11:05
  • if you have the webapp running in a virtual dir, you could/should use `var url = Request.Url.ToString().Substring(0, Request.Url.ToString().LastIndexOf('/')) + "/WebForm1.aspx";` – JP Hellemons Aug 20 '13 at 12:52
  • There's a problem with this if you deploying to a environment where your using a application folder.... – MiloTheGreat Dec 10 '15 at 07:48
1

You need an answer that works when you roll out to a different environment that maybe has a virtual application folder.

// r is Request.Url
var url = new Uri(r, System.Web.VirtualPathUtility.ToAbsolute("~/Folder/folder/page.aspx")).AbsoluteUri;

This will work in all cases and no nasty surprises when you deploy.

MiloTheGreat
  • 710
  • 7
  • 14
0

I suspect you're using the ASP.NET development server that's built-in to Visual Studio, which has a tendency to change port numbers by default. If that's the case, then you might try simply configuring the development server to always use the same port, as described here. Then just add the port number to your URL, like so:

private const string DummyPageUrl = 
"http://localhost:42001/TestCacheTimeout/WebForm1.aspx";
Community
  • 1
  • 1
David Mills
  • 2,385
  • 1
  • 22
  • 25