How to prevent static files opening without login in ASP.NET MVC

Hello,
If you are working on mvc application, and uploading pdf, images in your application than you have to prevent those files to open without login the application.
for this you have to use HttpHandler in MVC.

First you have to enable debug mode for static files from WebConfig, because static files route does not go in application pipeline.

Step 1 Enable runAllManagedModulesForAllRequests in webconfig and put Custom httphandler in


<system.webServer>
....
 <modules runAllManagedModulesForAllRequests="true" />
    <handlers>
      <add name="PDF" path="*.pdf" verb="GET" type="ApplicationNameSpace.FileProtectionHandler" resourceType="File" />
      <add name="JPG" path="*.jpg" verb="GET" type="ApplicationNameSpace.FileProtectionHandler" resourceType="File" />
      <add name="PNG" path="*.png" verb="GET" type="ApplicationNameSpace.FileProtectionHandler" resourceType="File" />
      <add name="BMP" path="*.bmp" verb="GET" type="ApplicationNameSpace.FileProtectionHandler" resourceType="File" />
    </handlers>
....
</system.webServer>

Step 2 : Create Custom HttpHandler in RouteConfig file, You can create a separate class instead in App_Start folder.
Here is Complete route.config

Here you have to implement 2 interfaces IHttpHandler and IRequiresSessionState.

namespace ApplicationNamespace
{
 public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
            );
        }
    }


    public class FileProtectionHandler : IHttpHandler, IRequiresSessionState
    {
        public bool IsReusable { get { return true; } }

        public void ProcessRequest(HttpContext context)
        {
            switch (context.Request.HttpMethod)
            {
                case "GET":
                    {
                        if (SessionHelpers.Userid != 0) // if Application is Login
                        {
                            string requestedFile = context.Server.MapPath(context.Request.FilePath);

                            SendContentTypeAndFile(context, requestedFile);
                        }
                        else
                        {
                            if (context.Request.FilePath.Contains("LoginPageLogo")) //it used for login page logo
                            {
                                string requestedFile = context.Server.MapPath(context.Request.FilePath);
                                SendContentTypeAndFile(context, requestedFile);
                            }
                            else
                            {
                                context.Response.Redirect("~/Account/Login");
                            }
                        }
                        break;
                    }
            }

        }

        private HttpContext SendContentTypeAndFile(HttpContext context, String strFile)
        {
            context.Response.ContentType = GetContentType(strFile);
            context.Response.TransmitFile(strFile);
            context.Response.End();
            return context;
        }
        private string GetContentType(string filename)
        {
            // used to set the encoding for the reponse stream
            string res = null;
            FileInfo fileinfo = new FileInfo(filename);
            if (fileinfo.Exists)
            {
                switch (fileinfo.Extension.Remove(0, 1).ToLower())
                {
                    case "pdf":
                        {
                            res = "application/pdf";
                            break;
                        }
                }
                return res;
            }
            return null;
        }
    }
}

Here we are handling appplication login trough Session, if there is session Userid that we saved on Login Time, if it is found than file will out through response.
You have to use those methods SendContentTypeAndFile and GetContentType for file out response.