How to use Url.Action() in a class file?

Erçin Dedeoğlu picture Erçin Dedeoğlu · Jan 1, 2014 · Viewed 24.5k times · Source

How can I use Url.Action() in a class file of MVC project?

Like:

namespace _3harf
{
    public class myFunction
    {
        public static void CheckUserAdminPanelPermissionToAccess()
        {
            if (ReferenceEquals(HttpContext.Current.Session["Loged"], "true") &&
                myFunction.GetPermission.AdminPermissionToLoginAdminPanel(
                    Convert.ToInt32(HttpContext.Current.Session["UID"])))
            {
                HttpContext.Current.Response.Redirect(Url.Action("MainPage", "Index"));
            }
        }
    }
}

Answer

Simon Belanger picture Simon Belanger · Jan 1, 2014

You will need to manually create the UrlHelper class and pass the appropriate RequestContext. It could be done with something like:

var requestContext = HttpContext.Current.Request.RequestContext;
new UrlHelper(requestContext).Action("Index", "MainPage");

However, you are trying to achieve redirection based on authentication. I suggest you look at implementing a custom AuthorizeAttribute filter to achieve this kind of behavior to be more in line with the framework