Asp MVC Action链接绝对url
我有一组显示给特定用户的视图。 这些是我从我们的应用程序中的其他视图复制的视图,并稍微更改了它们。
在这些视图中我使用的是Html.Action链接,但是我需要这些来返回绝对URL而不是相对。 我知道有额外的参数可以用来获得这种效果,但我不认为它可以改变我所有视图中的所有链接。
理想情况下,我想在一个地方进行更改,并根据需要渲染我的所有链接。 当然必须有我可以设置的东西,或者我可以覆盖的function来实现这一点。
我写了一篇名为“ 如何使用UrlHelper类构建绝对操作URL”的博客文章,其中我提供了一个名为AbsoluteAction
的自定义扩展方法。 我鼓励你看看吧!
/// /// Generates a fully qualified URL to an action method by using /// the specified action name, controller name and route values. /// /// The URL helper. /// The name of the action method. /// The name of the controller. /// The route values. /// The absolute URL. public static string AbsoluteAction(this UrlHelper url, string actionName, string controllerName, object routeValues = null) { string scheme = url.RequestContext.HttpContext.Request.Url.Scheme; return url.Action(actionName, controllerName, routeValues, scheme); }
ASP.NET MVC包含用于生成绝对URL的内置function,但不是以非常直观的方式。
UrlHelper.Action()
方法有几个重载,使您可以传递其他参数,如路由值,要使用的协议和URL的主机名。 如果您使用任何允许您指定protocol
参数的重载,则生成的URL将是绝对的。 因此,以下代码可用于为HomeController的About操作方法生成绝对URL:
@Url.Action("About", "Home", null, "http")
您可以创建一个名为Html.AbsoluteAction的新扩展方法。 AbsoluteAction可以添加使URL绝对所需的额外参数,因此您只需在自定义扩展方法中编写一次该代码。