Alex Rivera | Logout

Getting URL to action in static method in ASP.NET MVC

Asked 2011-08-16T17:37:32.180
10

My ASP.NET MVC application adds a route named "Asset" to the RouteTable, and I have a static method.

This static method needs to be able to generate the URL to the "Asset" route of the application.

How can I do this?

Edit
Report

1 Answer

2

The helper class:

  public static class UrlHelper
  {
    private static System.Web.Mvc.UrlHelper _urlHelper;

    public static System.Web.Mvc.UrlHelper GetFromContext()
    {
      if (_urlHelper == null)
      {
        if (HttpContext.Current == null)
        {
         throw new HttpException("Current httpcontext is null!"); 
        }

        if (!(HttpContext.Current.CurrentHandler is System.Web.Mvc.MvcHandler))
        {
          throw new HttpException("Type casting is failed!"); 
        }

        _urlHelper = new System.Web.Mvc.UrlHelper(((System.Web.Mvc.MvcHandler)HttpContext.Current.CurrentHandler).RequestContext);
      }

      return _urlHelper;
    }
  }

The calling:

UrlHelper.GetFromContext().Action("action", "controller");
answered 2012-01-23T21:03:04.147

Your Answer