如何使用具有密码保护的MVC4/Razor下载文件



控制器函数中有一个链接,下载文件的唯一问题是链接上具有密码身份验证,是执行身份验证并制作的适当方法在身份验证用户名和密码后可下载链接。这是我的控制器功能:

[HttpGet]
public ActionResult ImportData()
{
    System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/App_Data/TempData/DataFile"));
    foreach (FileInfo csvfile in di.GetFiles())
    {
        csvfile.Delete();
    }
    MyWebClient webClient = new MyWebClient();
    webClient.DownloadFile("http://gis.abc.org.pk/report.php", Server.MapPath("~/App_Data/TempData/DataFile/Data.csv"));
    using (ApplicationDbContext db = new ApplicationDbContext())
    {
        db.Database.ExecuteSqlCommand("SP_BulkInsertData");
        db.Database.ExecuteSqlCommand("SP_InsertData");
        db.Database.ExecuteSqlCommand("SP_VillageLevelDataCreation");
    }
    // return View();
    return RedirectToAction("ImportSendMail");
}

我不确定您使用的是什么是MyWebClient,但您可以简单地使用.NET WebClient并设置凭据。以下是示例代码。

using (WebClient webClient = new WebClient())
{
    webClient.Credentials = new NetworkCredential(username, password); //set username and password here
    webClient.DownloadFile("http://gis.abc.org.pk/report.php", Server.MapPath("~/App_Data/TempData/DataFile/Data.csv"));
}

最新更新