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?

2 Answers 2

17

assuming your code is running in the context of a http request, you can do the following from a static method:

new UrlHelper(HttpContext.Current.Request.RequestContext);
Sign up to request clarification or add additional context in comments.

Comments

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.