Asp MVC Action链接绝对URL

use*_*859 12 c# asp.net-mvc

我有一组显示给特定用户的视图.这些是我从我们的应用程序中的其他视图复制的视图,并稍微更改了它们.

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

理想情况下,我想在一个地方进行更改,并根据需要渲染我的所有链接.当然必须有我可以设置的东西,或者我可以覆盖的功能来实现这一目标.

Mar*_*ulz 12

我写了一篇名为" 如何使用UrlHelper类构建绝对操作URL"的博客文章,其中我提供了一个名为的自定义扩展方法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);
}
Run Code Online (Sandbox Code Playgroud)

ASP.NET MVC包含用于生成绝对URL的内置功能,但不是非常直观.

有几种重载UrlHelper.Action()方法可以让您传递其他参数,例如路由值,要使用的协议和URL的主机名.如果您正在使用允许您指定protocol参数的任何重载,则生成的URL将是绝对的.因此,以下代码可用于为HomeControllerAbout操作方法生成绝对URL :

@Url.Action("About", "Home", null, "http")
Run Code Online (Sandbox Code Playgroud)


Dav*_*sky 2

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