0

how can I set about c # MVC viewing files with absolute path (eg. www.mysite.it/namefile.pdf) only for authenticated users ? for authentication use the method FormsAuthentication.Authenticate(). thanks for the support.

Mic
  • 5
  • 5
  • Are all the files you want to restrict access to in the root of the site? Coudl you move them into a subfolder? – Carl Feb 24 '15 at 20:31

2 Answers2

2

I think that the more properly way to do that is:

www.mysite.it/f={filename}

And in your controller you use the [Authorize] to check if user is authenticated. If the user is authenticated you allow him to view, or download, the file.

The following code can help you to understand:

//Ensure that the user is authenticated
[Authorize]
public class HomeController : Controller
{
    string DefaultFileFolder = "C:/Files";

    public ActionResult Index(string f)
    {
        //File request
        if (!String.IsNullOrWhiteSpace(f))
        {
            var filePath = System.IO.Path.Combine(DefaultFileFolder, f);
            var mimeType = "text/plain";

            return File(filePath, mimeType);
        }

        return View();
    }
}
Richard Dias
  • 220
  • 3
  • 10
  • hello you give me an example? I'm afraid I did not understand well what the solution – Mic Feb 25 '15 at 08:20
  • Thanks a lot , it works perfectly , you have to add your code with the modification suggested by @JasonCoder on web.config – Mic Feb 25 '15 at 15:42
0

As far as I know the only way to do this is to route requests for static content through ASP.NET. Normally you don't do this as IIS by itself is far more efficient at serving these types of resources.

From this excellent article, you can force static content requests to go through ASP.NET by:

On IIS 7 this is done either by setting runAllManagedModulesForAllRequests=”true” or removing the "managedHandler" preCondition for the UrlRoutingModule.

Depending on your needs, you may wish to do something more in line with what Richard suggested. Something like this perhaps?

Community
  • 1
  • 1
JasonCoder
  • 1,126
  • 2
  • 12
  • 24
  • 1
    Hello @JasonCoder thanks for the reply ; I added this code in web.config ` ` , but how do I show the files to users logged in to the site? because now that I added the code I do not see the file even if the user is logged in – Mic Feb 25 '15 at 12:03