Introduction
Here is writing another article to make more secure of your MVC application. I’ll explore all aspects here, how to prevent direct URL access in MVC application. Before to go through this article, you are required to detail about these articles as given below.- Asp.net mvc session management example
- Prevent Cross-Site Request Forgery using AntiForgeryToken() in MVC
Namespace Used
To apply this feature into your MVC application is used System.Web.Routing namespace to prevent direct URL access in MVC.using System.Web.Routing
Apply this feature in FilterConfig.cs file
We have to call this feature under OnActionExecuting of Action filter. We have to apply filter as below written lines to prevent direct URL access in MVC. If we are tempering URL in browser then it will forcibly throw you to Logout action of Home Controller lying under Main area.[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 = "Home", action = "Logout", area = "Main" })); } } }
Prevent Direct Access to Class (Apply on Controller Class)
We can apply NoDirectAccess Attribute to Class and it will follow to all containing methods, if any methods accessed directly under the whole controller. It will throw you specified action (here’s throwing Logout action) like MyWebsiteURL.com/Main/PersonalDetail/Index[NoDirectAccess] public class PersonalDetailController : Controller { // // GET: /Main/PersonalDetail/ public ActionResult Index() { return View(); } }
Apply NoDirectAccess Attribute to Action
Alternatively, we can apply NoDirectAccess Attribute to specific Action rather than to whole Controller class. Suppose, we are accessing directly like MyWebsiteURL.com/Main/Home/login[NoDirectAccess] public ActionResult Login() { return View(); }
Post A Comment:
0 comments: