There are many ways to block/restrict controller from
outside world. Here is some possible solution for same
1)
We can writer custom filter to prevent the
controller from being execute and use the customer as attribute
2)
Within delegating handler we can write some code
to sniff controller from current http context and block there.
3)
We can implement custom routing mechanism to
prevent some controller from being execute.
In this article we will implement custom route class by
implement IRouteConstant interface. The class can be use in time route
initialization. Let’s implement the class at first.
public class ExcludeController : IRouteConstraint
{
private readonly string _controller;
public ExcludeController(string controller)
{
_controller = controller;
}
public bool Match(HttpContextBase httpContext, Route route,
string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return ! string.Equals(values["controller"].ToString(),
_controller, StringComparison.OrdinalIgnoreCase);
}
}
Formally, the class name is ExcludeController. We have
implemented Match() function within class. It will return false when current controller
name will equal to restricted controller name. Now, we have to fit the class in
route definition. Here is how, we can fit the class in route entry.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
},
constraints: new { controller = new ExcludeController("Configuration")
}
);
Please note that, we are passing parameter value “Configuration”
that implies, when request will come for Configuration controller it will just
ignore because Match() function will return false.
Here is sample code for Configuration controller.
public class ConfigurationController : Controller
{
public ActionResult Index()
{
return new EmptyResult();
}
}
And it’s throwing 404 result when we are trying to execute.
No comments:
Post a Comment