开发者

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

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?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜