Question

Basically I need to serve files from a location that requires windows authentication. Instead of having my client's deal with it directly, I would like to implement a process so that they can simply download the files as if they were on my server, after they have logged in to my system, of course. Here is what I have so far, which doesn't seem to work correctly:

// Create the request
WebRequest request = HttpWebRequest.Create(button.CommandArgument);
request.Credentials = new NetworkCredential(_username,_password);


// Get the response
WebResponse response = request.GetResponse();
StreamReader responseStream = new StreamReader( response.GetResponseStream());

// Send the response directly to output
Response.ContentEncoding = responseStream.CurrentEncoding;
Response.ContentType = request.ContentType;
Response.Write(responseStream.ReadToEnd());
Response.End();

When I try this I am able to view the file, but something is wrong with the encoding or the content type and, for example, a PDF will contain 16 blank pages (Instead of 16 pages of text).

Any idea what am I missing?

Feel free to change the title of this question if there is a better way of phrasing this question

Update: Tried the two responses below but with no luck. I now think that the content type and encoding are OK, but maybe the authentication is failing? The content-length is a lot smaller than it actually should be... Am I using the wrong method for Windows Authentication?

Was it helpful?

Solution

Depending on how/what you have. I would do a few things.

Response.Clear() first of all to remove anything that might have been rendered.

I would then add a header, with content-disposition set and send it down as an actual attachment, rather than just writing it to the user.

OTHER TIPS

It looks like you're sending the wrong content type in your last code block. You're sending the type of the user's original request instead of the content type of the file that you've retrieved. Change this:

Response.ContentType = request.ContentType;

to:

Response.ContentType = response.ContentType;

If your problem is related to network credentials, you may want to try a different approach. If you grant HTTP access to the identity that the web site's application pool is using, you can avoid having to specify the username/password credentials in the request. This also gives you the added benefit of not needing to store the password somewhere.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top