Mvc*_*012 10 asp.net-mvc asp.net-mvc-routing
我的ASP.NET MVC应用程序添加了一个名为"Asset"的路由RouteTable
,我有一个静态方法.
此静态方法需要能够生成应用程序的"Asset"路由的URL.
我怎样才能做到这一点?
小智 17
假设您的代码在http请求的上下文中运行,您可以从静态方法执行以下操作:
new UrlHelper(HttpContext.Current.Request.RequestContext);
Run Code Online (Sandbox Code Playgroud)
辅助类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
召唤:
UrlHelper.GetFromContext().Action("action", "controller");
Run Code Online (Sandbox Code Playgroud)