我使用Handler请求访问一个站点。需要访问该站点文件并下载。该站点需要用户和密码,才能访问。现在代码当中虽然有通过 HttpWebRequest 中Credentials 属性进行用户验证。
HttpWebRequest httpWebRequest= httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(filePath);
NetworkCredential credential= new NetworkCredential(user, passWord);
httpWebRequest.Credentials = credential;
但每次点击访问该站点上的文件,还是跳出用户登陆框提示。怀疑是代码当中,用户验证和保存到客户端不在同一进程中。该问题需要如何处理?期待大家的方案。
源码:
Code
public class AutoDownloadHandler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
string fileName = “地址栏传入的文件名参数”
string siteUrl = System.Configuration.ConfigurationManager.AppSettings["FtpUrl"].ToString();
string user = System.Configuration.ConfigurationManager.AppSettings["FtpUser"].ToString();
string passWord = System.Configuration.ConfigurationManager.AppSettings["FtpPassWord"].ToString();
try
{
string filePath = siteUrl + fileName;
HttpWebRequest httpWebRequest;
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(filePath);
NetworkCredential credential= new NetworkCredential(user, passWord);
httpWebRequest.Credentials = credential;
HttpWebResponse httpWebResponse;
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
MemoryStream stmMemory = new MemoryStream();
byte[] buffer = new byte[64 * 1024];
int i;
while ((i = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
stmMemory.Write(buffer, 0, i);
}
byte[] arrayByte = stmMemory.ToArray();
stmMemory.Close();
responseStream.Close();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = GetMimeType(fileName);
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AppendHeader("Content-Length", arrayByte.Length.ToString());
HttpContext.Current.Response.BinaryWrite(arrayByte);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
}
}
#endregion
}