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

时间:2017-12-26 09:29:20

标签: c# asp.net asp.net-mvc asp.net-mvc-4 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");
}

1 个答案:

答案 0 :(得分:1)

我不确定您使用的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"));
}