Sadia
Sadia

Reputation: 181

How to download file with MVC4/Razor having password protection

There is a link inside controller function through which a file is downloaded the only issue is that the link has password authentication on it ,what would be the appropriate method to perform the authentication and make the link downloadable after authenticating username and password. Here is my controller function:

[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");
}

Upvotes: 0

Views: 206

Answers (1)

Souvik Ghosh
Souvik Ghosh

Reputation: 4616

I am not sure what is MyWebClient that you are using but you can simply use .Net WebClient and set credentials. Below is the sample code.

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"));
}

Upvotes: 1

Related Questions