Mic
Mic

Reputation: 5

C # MVC view files only for logged in users

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.

Upvotes: 0

Views: 2205

Answers (2)

Richard Dias
Richard Dias

Reputation: 230

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

Upvotes: 2

JasonCoder
JasonCoder

Reputation: 1136

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?

Upvotes: 0

Related Questions