Deny direct URL access to action method

前端 未结 5 1946
深忆病人
深忆病人 2021-02-04 11:56

I\'m trying to find a way to deny any direct access to my action methods. Basically what I want my users to click on links to navigate instead of typing the URL directly into th

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 12:07

    Use this code in Global.asax.cs and Call [NoDirectAccess] to all controllers

        //Prevent direct URL access: Call [NoDirectAccess] to all controllers to block
        [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 = "Login", area = "" }));
                }
            }
        }
    

提交回复
热议问题