Haikal Nashuha
Haikal Nashuha

Reputation: 3048

Htmlfile access is denied when using Server.MapPath

I have been using Server.MapPath("page.aspx") for quite a long time, but it is just now that I faced this problem.

Basically here is my code

Session.Clear();
ShowLoggedOffControl(); //A function that setup bunch of controls visibility
OnUserLoggedOut(new EventArgs());
Response.Redirect(Server.MapPath("~/Default.aspx"));

The error would be htmlfile:access is denied at javascript execution. However when I removed Server.MapPath so that it became like this Response.Redirect("~/Default.aspx");, things work normally.

What did I do wrong? Why, how and when can I use Server.MapPath?

Thanks.

Upvotes: 1

Views: 1136

Answers (2)

James Johnson
James Johnson

Reputation: 46057

Server.MapPath gets the physical path to the file on the hard disk, whereas Response.Redirect expects a URL.

If for some reason you need to get the full URL, you can use this:

String.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));

Upvotes: 0

Gordon Tucker
Gordon Tucker

Reputation: 6773

Server.MapPath maps the specified relative or virtual path to the corresponding physical directory on the server. So in your example it would end up redirecting to something like this:

c:\Projects\MyWebsite\Default.aspx

which is probably not what you want.

Response.Redirect on the other hand will resolve the '~' to the relative path root for you and resolve to something like this:

/MyVirtualDirectory/Default.aspx

As for when you would want to use Server.MapPath, you would use it if you wanted to actually find the file on the server and do something such as:

var lines = System.IO.File.ReadAllLines(Server.MapPath("~/MyTextFile.txt"));
// Do something here with values found

Upvotes: 2

Related Questions