Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I have to restrict access to particular action in a controller and so i have created a RestrictAccess attribute which implements ActionFilterAttribute .

RestrictAccess

C#
public class RestrictAccess : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

           filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary {{ "Controller", "Test" },                                   
                                              { "Action", "RedirectToError" } });
            base.OnActionExecuting(filterContext);
        }
    }


While debugging , after executing above code it is supposed to redirect and go hit the TestController's RedirectToError action. But it fails to redirect .

Test Controller:
public ActionResult RedirectToError()
{
    return View("AccessRestriction.cshtml");
}


Instead i get this below error in browser.
Endpoint not found. Please see the service help page for constructing valid requests to the service.

Can someone help me in this?

What I have tried:

I have tried overriding unauthorizedRequest as well. Still same issue.

C#
public class RestrictAccess : AuthorizeAttribute
{
   public override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
       UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
       filterContext.Result = new RedirectResult(urlHelper.Action("Test", "RedirectToError"));
   }
}
Posted
Updated 6-Jan-18 7:44am

1 solution

In the HandleUnauthorizedRequest method try using the following syntax and make sure you register the filter (RestrictAccess) in the FilterConfig

C#
filterContext.Result = new RedirectResult("~/Test/RedirectToError");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900