MVC操作链接绝对URL

MVC操作链接绝对URL

本文介绍了ASP MVC操作链接绝对URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组显示给特定用户的意见。这些意见我已经在我们的应用程序的其他视图复制,并改变了小幅上涨。

I have a set of views that display to specific users. These are views I've copied from other views in our app, and changed them slightly.

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

In these views I'm using Html.Action link, but I need these to return an absolute url instead of the relative. I know there are extra parameters that can be used to get this effect, but I dont tihnk its viable to change all my links in all my views.

在理想情况下I'de喜欢做在一个地方的变化,并有要求我的所有链接呈现。当然一定有什么东西我可以设置,或者我可以覆盖一个函数来完成这个任务。

Ideally I'de like to make a change in one place and have all my links render as required. Surely there must be something I can set, or a function I can override to accomplish this.

推荐答案

我编写了一个博客帖子How建立使用UrlHelper类我在其中present命名的自定义扩展方法 AbsoluteAction 绝对行动的网址。我鼓励你去瞧瞧吧!

I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I present a custom extension method named AbsoluteAction. I encourage you to check it out!

/// <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的产生,虽然不是在一个非常直观的方式。


ASP.NET MVC includes built-in functionality for the generation of absolute URLs, though not in a very intuitive way.

的几个重载UrlHelper.Action()方法,使您能够传递更多的参数,如路由值,要使用的协议和URL中的主机名。如果你正在使用的任何重载允许您指定协议参数,生成的URL将是绝对的。因此,下面的code可用于生成的关于的行动方法的的HomeController 的绝对网址:

There are several overloads of UrlHelper.Action() method that enable you to pass additional parameters like route values, the protocol to use and the host name for the URL. If you are using any overload that allows you to specify the protocol parameter, the generated URL will be absolute. Thus, the following code can be used to generate an absolute URL for the About action method of the HomeController:

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

这篇关于ASP MVC操作链接绝对URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:03