Response.Redirect to a UNC path - asp.net

I'd like to redirect the user to a directory on a file server using its UNC path. I've tried using something like the following but I just get a 404 error.
Response.Redirect(#"file:\\fileserver\data\");
What's the correct syntax to make this work?

You don't quite have the file protocol identifier correct.
Try:
string location = String.Format("file:///{0}", #"\\fileserver\data\");
Response.Redirect(location, true);

I'm not sure about the Response.Redirect method, but you can always write the file for download by the user using Response.WriteFile.
This link might help: http://support.microsoft.com/kb/307603/EN-US/
Code Snippet from above link:
private void Page_Load(object sender, EventArgs e)
{
//Set the appropriate ContentType.
Response.ContentType = "Application/pdf";
//Write the file directly to the HTTP output stream.
Response.WriteFile(#"\\server\folder\file.pdf");
Response.End();
}

file:////server/directory
Or, create a virtual directory in your Website and map it to a path, like /data/

Related

How to add all the files in directory in ASP.NET and when i click on the link that file should get download?

I wanna to display all the files in a directory in ASP.NET. when i click on the list of files available in that it should get download to local or it should open to view?
How to achieve this ? i got all the files in directory but i don't know to make those files to download?
Thanks in advance.
In order to make the file downlodble you have to add for each file an href
eg
foreach(string fileName in Dir)
{
Response.Write("<a href='"+fileName+"'>file name...</a>");
}
ore you have to force download in such way
public static void ForceDownload(this HttpResponse Response, string virtualPath, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.WriteFile(virtualPath);
Response.ContentType = "";
Response.End();
}
One way to do this is to enable directory browsing in IIS.
For whatever reason, directory browsing also displays the web.config file for the directory. The following link discuses how to not show it: http://forums.iis.net/t/1149484.aspx/1

Redirect Web Page Requests to a Default Sub Folder

I am using UltiDev Web Server Pro and have all my aspx files are located in a sub folder 'WebForms'.
I want to be able to default all requests for pages to this folder such that they can just type:
http://myserver/somepage.aspx instead of
http://myserver/WebForms/somepage.aspx.
Is this possible?
EDIT:
Here is the VB.NET version of the solution below including a check for case sensitivity:
If Not HttpContext.Current.Request.Path.ToUpper.Contains("/WEBFORMS/") Then
Context.RewritePath("/WebForms" + HttpContext.Current.Request.Path, False)
End If
You can use the Global.asax and the Application_BeginRequest to RewritePath to the final destination and still have the link without the WebForm path.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if(!HttpContext.Current.Request.Path.Contain("/WebForms/"))
RewritePath("/WebForms" + HttpContext.Current.Request.Path, false);
}

how to open a file by its full path?

I have a GridView which has following template field that holds the filename, when the user clicks the filename, I call window.open() to open the file. My question is I can only pass relative path to window.open(). I got an error if I use full path. Is there any way I can use full path to open a file? Thanks.
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:LinkButton ID="lnkFile" runat="server"
Text='<%# Eval("FileName")%>' OnClick="lnkFile_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Added: The actual location of the file is defined in web.config.
I have wrote following lnkFile_Click(). The old part will open a new window for the file, but I cannot pass fullpath of the file. The new part will let you have a choice to open or save the file. My question is, will this cause security issue?
protected void lnkFile_Click(object sender, System.EventArgs e)
{
string fileName = ConfigurationSettings.AppSettings["SPRAttachmentLocation"] + "\\SPR" + sprID + "\\" + ((LinkButton)sender).Text;
if (!File.Exists(fileName))
{
Exception ex = new Exception("Could not find the file, please contact your administrator.");
Response.Write("<p align=\"center\"><br /><br /><br /><br />There has been an Error: <strong>" + ex.Message + "</strong></p>\n");
return;
}
New:
byte[] bts = System.IO.File.ReadAllBytes(fileName);
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "");
Response.AddHeader("Content-Length", bts.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bts);
Response.Flush();
Response.End();
Old:
string newWindowUrl = "/SPR_Upload/SPR" + sprID + "/" + ((LinkButton)sender).Text;
string javaScript =
"<script type='text/javascript'>\n" +
"<!--\n" +
"window.open('" + newWindowUrl + "');\n" +
"// -->\n" +
"</script>\n";
Page.ClientScript.RegisterStartupScript(GetType(), "", javaScript);
}
Your question gives the impression that you think that you can open a file from the user's local computer. If that's the case, this is not possible.
Window.open expects a URL because the file is located on the server side, not the client side.
With that said, if you are trying to open a file located on the server side and you know the full path to the file; what you need to do is generate the virtual path within your application where the file can be found. You do this by creating a Virtual Directory in your APP from the IIS Admin Manager (Control Panel-->Admin Tools -->IIS Mgmt) and mapping this directory to the actual physical directory.
EDIT:
Say for example your whole website is physically located on the server on c:\inetpub\wwwroot\your_app. Let's assume your app can be accessed via http://example.com and the files you want to serve are physically located on d:\files. Assume further that you created a virtual directory for your app (as I explained above) and that you called this virtual folder public_files. If one knows the file name it should be possible to access the file by simply going to http://example.com/public_files/filename.ext. Since you in your app already know the file name, all you need to pass as parameter to window.open is this url (http://example.com/public_files/filename.txt)
You could try using the AppDomainAppVirtualPath to get the virtual path to the file.
string vPath = HttpRuntime.AppDomainAppVirtualPath + "/my/relative/path"
if the file is not located within the virtual directory there are a number of security issues you need to consider and address. in general it's not a good idea to access a file outside of the virtual directory.
if you must, then you will need to raise security permissions and grant access to the file on the network.

is there any IIS setting require for url rewriting?

i have used URL rewriting using global.asax file. url rewriting is working file on local machine but when i made it online its not working.
void Application_BeginRequest(Object sender, EventArgs e)
{
var extension = Path.GetExtension(Request.PhysicalPath).ToLower();
if (File.Exists(Request.PhysicalPath))
{
if (extension == ".html")
{
Response.WriteFile(Request.PhysicalPath);
Response.End();
}
return;
}
var path = Request.Path;
if (!Context.Items.Contains("ORIGINAL_REQUEST"))
Context.Items.Add("ORIGINAL_REQUEST", path);
if (extension == ".html")
{
var resource = UrlRewriting.FindRequestedResource();
var command = UrlRewriting.GetExecutionPath(resource);
Context.RewritePath(command, true);
}
}
url is:ind205.cfmdeveloper.com
when you click on about us ,demo,advertise page it will not display.
so please let me know is there any IIS setting require,
reply me soon
thanks
Samir
I work on url rewriting. I don't think it need any setting in IIS as i work in it and i didn't made any changes in url writing by the way you can see these links.hopefully you get any solution from them.
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx
http://learn.iis.net/page.aspx/496/iis-url-rewriting-and-aspnet-routing/
http://learn.iis.net/page.aspx/517/url-rewriting-for-aspnet-web-forms/
http://www.asp.net/learn/Videos/video-154.aspx
http://www.15seconds.com/Issue/030522.htm
http://urlrewriter.net/
If you got your answer from these links check my answer and also vote it.thanx
I notice that you have .html file that you check for. For html to pass from asp.net processing , you need to declare it (map it) ether on iis ether on web.config

Why my httpwebrequest post to myhandler.ashx is rejected with status code 401

I've already written an HTTPHandler that gets POSTed from a ColdFusion page and it works successfully; now, I am trying to write a web application in ASP.NET so I can post a form to the .ashx handler from an .aspx page.
Application Trace (trace.axd) shows the following as my last 3 entries:
2 8/14/2009 1:53:56 PM /Default.aspx 200 GET View Details
3 8/14/2009 1:54:04 PM /Default.aspx 200 POST View Details
4 8/14/2009 1:54:13 PM /UploadHandler.ashx 401 POST View Details
I have a breakpoint in my .ashx file but it is never reached (I guess because of the 401 status code). Here is the snippet of code from the default.aspx trying to POST to the handler:
protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(BuildFormData());
string baseAddress = "http://" + Environment.MachineName;
string pathInfo = Page.ResolveUrl("UploadHandler.ashx");
string URI = baseAddress + pathInfo;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URI);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
}
catch (Exception someError)
{
LogText("FAILURE: " + someError.Message);
}
}
}
Here is a snippet of code from the UploadHandler.ashx file (but this doesn't appear to be reached):
public void ProcessRequest(HttpContext context)
{
string returnURL = context.Request.ServerVariables["HTTP_REFERER"];
string message;
message = UploadFile(context);
StringBuilder msgReturn = new StringBuilder(returnURL);
msgReturn.Append("?n=");
msgReturn.Append(HttpUtility.UrlEncode(TRIMrecNumAssigned));
msgReturn.Append("&m=");
msgReturn.Append(HttpUtility.UrlEncode(message));
context.Response.Redirect(msgReturn.ToString());
}
Both default.aspx and UploadHandler.ashx are in the root of a virtual directory on my localhost; the directory security is currently set to "Anonymous access" CHECKED and "Integrated Windows authentication" CHECKED.
When I click the "View Details" link on the trace.axd display, I see all the data in the Forms collection that I expect to see and hope to process but this 401 seems to be stopping everything. I could post the code for my little function called BuildFormData() if useful.
EDIT: Revised handler as follows (has had no effect; same error occurs):
public void ProcessRequest(HttpContext context)
{
//-----------------------------------------------------------------------------------------
// the remainder of this block is alternative to the .Redirect and is useful for debugging.
context.Response.ContentType = "text/html";
//context.Response.Write(TRIMrecNumAssigned);
//context.Response.Write("<p>");
//context.Response.Write(msgReturn);
context.Response.Write("<H1>Trim - Kerberos Prototype for ColdFusion consuming pages</h1>");
HttpContext.Current.Trace.IsEnabled = true;
HttpContext.Current.Trace.Write(null);
HttpContext.Current.Trace.Write("-------");
HttpContext.Current.Trace.Write(context.Request.Form["txtTrimRecordType"]);
HttpContext.Current.Trace.Write(GetUserInfo());
HttpContext.Current.Trace.Write("-------");
HttpContext.Current.Trace.Write(null);
using (Html32TextWriter htw = new Html32TextWriter(context.Response.Output))
{
typeof(TraceContext)
.GetMethod("Render", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(HttpContext.Current.Trace, new object[] { htw });
}
}
Have you tried turning off Integrated Windows Auth and just leaving anonymous checked? Does it make a difference?
Your answer: "I think it made things worse because now I cannot even browse to default.aspx. I get this: HTTP 401.3 - Access denied by ACL on resource Internet Information Services"
My response: This is actually a good thing. This means we're getting closer to what is going on. If you're getting that error message and the only thing you have enabled is anonymous authentication via IIS, that means that the ASP.NET impersonation user doesn't have NTFS permissions on the files in question.
I'm not sure if you are on XP or Win 2k3, but now you want to check and make sure that either the ASPNET (XP) or Network Service (Win 2k3) users have at least read access on the files in question. Make sure that user has at least that level of access and then let me know how it goes.
Update: I don't know why I didn't think of this before. You may need to set credentials on your HttpWebRequest. To use the credentials of the current user, try adding this to your request.
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URI);
myRequest.Credentials = CredentialCache.DefaultCredentials;
If you need to add different credentials you can try Network Credentials
There's a good explanation of credentials here.
Hope this helps.
Looking at your ProcessRequest(), you do the following:
string returnURL = context.Request.ServerVariables["HTTP_REFERER"];
Based on how you are calling it with HttpWebRequest, this variable will be null. Then when you create your msgReturn, it will look something like this:
?n=XXX%m=YYY
When you redirect to this URL, it will probably not be found which is what is returning the 401.

Resources