Wednesday, July 4, 2018

Restrict modifying the URL or Route in MVC

To restrict the user from modifying the URL. Write the following code in the Global.asax.cs file.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
        public class NoDirectAccessAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (filterContext.HttpContext.Request.UrlReferrer == null ||
                            filterContext.HttpContext.Request.Url.Host != filterContext.HttpContext.Request.UrlReferrer.Host)
                {
                    filterContext.Result = new RedirectToRouteResult(new
                                   RouteValueDictionary(new { controller = "Error", action = "Index", area = "" }));
                }
            }
        }

Then add this Action Filter to Controller [MvcApplication.NoDirectAccess]

No comments:

Post a Comment

Git Commands

Git Version   To check the git version Git -v       Git Clone To clone the repository, use the following command: Git clone [u...