2010-10-05 109 views
11

我有一组显示给特定用户的视图。这些是我从我们的应用中的其他视图中复制的视图,并稍微改变了它们。Asp MVC操作链接绝对url

在这些视图中我使用Html.Action链接,但我需要这些返回绝对url而不是相对。我知道有一些额外的参数可以用来获得这种效果,但是我不想在我所有的观点中改变我所有的链接。

理想情况下,我想在一个位置进行更改,并根据需要显示所有链接。当然,必须有一些我可以设置的东西,或者我可以重写的功能来实现这一点。

回答

2

您可以创建一个名为Html.AbsoluteAction的新扩展方法。 AbsoluteAction可以添加必要的额外参数以使URL绝对化,因此您只需在自定义扩展方法中编写一次该代码即可。

+0

,因为我知道这是做到这一点的唯一方法。无论哪种方式,你将不得不更新你的所有链接,以工作。不确定在Html.Action中拥有绝对链接的理由... – 2010-10-05 13:43:36

11

我写了一篇名为How to build absolute action URLs using the UrlHelper class的博客文章,其中介绍了一个名为AbsoluteAction的自定义扩展方法。我鼓励你看看!

/// <summary> 
/// Generates a fully qualified URL to an action method by using 
/// the specified action name, controller name and route values. 
/// </summary> 
/// <param name="url">The URL helper.</param> 
/// <param name="actionName">The name of the action method.</param> 
/// <param name="controllerName">The name of the controller.</param> 
/// <param name="routeValues">The route values.</param> 
/// <returns>The absolute URL.</returns> 
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的生成功能,虽然不是一个非常直观的方式。

UrlHelper.Action()方法有几个重载方法,它们允许您传递其他参数,如路由值,要使用的协议和URL的主机名。如果您使用的任何重载允许您指定参数,则生成的URL将是绝对的。因此,下面的代码可用于生成用于的HomeController关于操作方法绝对URL:据

@Url.Action("About", "Home", null, "http")