tags:

views:

22

answers:

1

Hello

I have this piece of code:

public class Authenticate : ActionFilterAttribute
{

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.HttpContext.Response.Redirect("/");   
        }
    } 
}

I was wondering if it is possible to make it redirect to the view for action="Login" controller="AdminLogin"? And how do I pass some message to the login view that tells "you need to login to access that" or similar?

/M

A: 

Here is how I solved the redirect-part:

public class Authenticate : ActionFilterAttribute
{

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            RedirectToRoute(filterContext,
                new
                {
                    controller = "AdminLogin",
                    action = "AdminLogin"
                });
        }
    }



    private void RedirectToRoute(ActionExecutingContext context, object routeValues)
    {
        var rc = new RequestContext(context.HttpContext, context.RouteData);

        string url = RouteTable.Routes.GetVirtualPath(rc,
            new RouteValueDictionary(routeValues)).VirtualPath;

        context.HttpContext.Response.Redirect(url, true);
    }

}

Not sure if it is optimal but seems to do the job correctly

molgan