Archive September 2019

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.

How to pass dictionary from JQuery Ajax to C# MVC Model

We have a model class in mvc c#, that also contains a dictionary property, and we want to pass data in this dictionary from jquery ajax.

Here we go,
We have a Model Class

 public class ModelClass
    {
      
        private Dictionary<string, string> _parameter= new Dictionary<string, string>();
        public Dictionary<string, string> Parameter{ get { return _parameter; } set { _parameter= value; } }
    }

And Here is Ajax and jquery code to send the dictionary as parameter


var parameter = [];
            parameter.push({ "key": "FromDate", "value": $('#FromDate').val() });
            parameter.push({ "key": "ToDate", "value": $('#ToDate').val() });
            
            var jsonParameters = { "Parameter": parameter };

            $.ajax({
                type: "POST",
                url: '@Url.Action("Home","Index")',
                contentType: 'application/json',
                data: JSON.stringify({ ModelClass: jsonParameters }),
                success: function (data) {
                    
                },
                error: function () {
                    alert('error');
                }
            })


And Here is controller that will accept parameters in ModelClass


public class HomeController : Controller
    {
       public ActionResult Index(ModelClass model) // Here You will get Dictionary as parameter
        {
            return View();
        }
    }