问题 Asp MVC Action链接绝对url


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

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

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


12417
2017-10-05 13:25


起源



答案:


我写了一篇名为的博客文章 如何使用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);
}

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

有几个重载 UrlHelper.Action() 使您能够传递其他参数(如路由值,要使用的协议和URL的主机名)的方法。如果您正在使用任何允许您指定的重载 protocol 参数,生成的URL将是绝对的。因此,以下代码可用于生成的绝对URL 关于 行动方法 HomeController的

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

11
2017-07-24 12:01





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


2
2017-10-05 13:29



据我所知,这是唯一的方法。无论哪种方式,您都必须更新所有链接才能使用。不确定在Html.Action中拥有绝对链接的理由...... - Bryce Fischer


答案:


我写了一篇名为的博客文章 如何使用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);
}

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

有几个重载 UrlHelper.Action() 使您能够传递其他参数(如路由值,要使用的协议和URL的主机名)的方法。如果您正在使用任何允许您指定的重载 protocol 参数,生成的URL将是绝对的。因此,以下代码可用于生成的绝对URL 关于 行动方法 HomeController的

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

11
2017-07-24 12:01





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


2
2017-10-05 13:29



据我所知,这是唯一的方法。无论哪种方式,您都必须更新所有链接才能使用。不确定在Html.Action中拥有绝对链接的理由...... - Bryce Fischer