I'm developing an application and I'm securing it using Fluent Security. I have 2 different areas within the web application, namely an Admin area and a Members area. I implemented my Policies Violation Handlers following the guidelines in the fluent security website. Everything works fine except that when an exception is thrown I need to redirect to an error page. These are different depending on which area you are. For instance, the ForbiddenAccess error page from the Admin area is different than the one from the Members Area.
My Implementation of IPolicyViolationHandler is the following.
public class DenyAnonymousAccessPolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
return
new RedirectToRouteResult(
new RouteValueDictionary(new { action = "AnonymousError", controller = "Error", area = "Admin" }));
}
}
I need to get where the error occurs so that when I redirect my area is either " Admin" or "Members" and I can't figure out how to get that information from the exception. If I can get that information, redirecting to the appropriate page is trivial. Any help, suggestions, or if not possible, a workaround is appreciated.
Thanks,
It is currently not possible to extract that information from FluentSecurity but it should be really easy to do anyway.
Below are two extensionmethods that should help you get the current area name.
public static string GetAreaName(this RouteData routeData)
{
object value;
if (routeData.DataTokens.TryGetValue("area", out value))
{
return (value as string);
}
return GetAreaName(routeData.Route);
}
public static string GetAreaName(this RouteBase route)
{
var areRoute = route as IRouteWithArea;
if (areRoute != null)
{
return areRoute.Area;
}
var standardRoute = route as Route;
if ((standardRoute != null) && (standardRoute.DataTokens != null))
{
return (standardRoute.DataTokens["area"] as string) ?? string.Empty;
}
return string.Empty;
}
An here's how you would use it:
public class DenyAnonymousAccessPolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
var areaName = routeData.GetAreaName();
return
new RedirectToRouteResult(
new RouteValueDictionary(new { action = "AnonymousError", controller = "Error", area = areaName }));
}
}
Feel free to add a feature request for it.