如何在ASP.NET MVC中将URL路径转换为完整或绝对URL? [英] How to convert url path to full or absolute url in ASP.NET MVC?

查看:87
本文介绍了如何在ASP.NET MVC中将URL路径转换为完整或绝对URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#中的ASP.NET MVC开发Web应用程序.但是我在检索完整或绝对URL时遇到问题.在ASP.NET MVC中,我们得到这样的URL. Url.Content(〜/path/to/page").它将返回路径/到/页面" .但是我想做的是有一个这样的字符串-〜/controller/action" .

I am developing Web Application using ASP.NET MVC in C#. But I am having a problem with retrieving full or absolute url. In ASP.NET MVC we get url like this. Url.Content("~/path/to/page"). It will return "path/to/page". But what I want to do is I have a string like this - "~/controller/action".

让我们考虑一下我的网站域名是www.example.com.如果我使用 Url.Content(〜/controller/action"),它将仅返回"controller/action".我想获取"www.example.com/controller/action" .我怎么能得到它?

Let's consider my website domain is www.example.com. If I use Url.Content("~/controller/action"), it will just return "controller/action". I want to get "www.example.com/controller/action". How can I get it?

推荐答案

如果可以使用控制器/动作名称...

您应使用 Url.为此,请使用Action() 方法.

You should use the Url.Action() method for this.

通常, Url.Action()将返回与您现在期望的类似,当仅提供Controller和Action名称时:

Typically, Url.Action() will return something similar to what you presently expect when provided with just the Controller and Action names :

// This would yield "Controller/Action"
Url.Action("Action","Controller"); 

但是,当您传入协议参数(即 http https 等)时,该方法实际上将返回完整的绝对URL.为了方便起见,您可以使用

However, when you pass in the protocol parameter (i.e. http, https etc.) then the method will actually return a complete, absolute URL. For the sake of convienence, you can use the Request.Url.Scheme property to access the appropriate protocol as seen below :

// This would yield "http://your-site.com/Controller/Action"
Url.Action("Action", "Controller", null, Request.Url.Scheme);

您可以在此处查看实际操作示例.

如果您只有相对URL字符串...

如果您只能访问相对URL之类的内容(例如,〜/controller/action ),那么您可能希望创建一个函数来扩展 Url的当前功能.Content()方法以支持提供绝对URL:

If you only have access to something like a relative URL (i.e. ~/controller/action), then you may want to create a function that will extend the current functionality of the Url.Content() method to support serving absolute URLs :

public static class UrlExtensions
{
    public static string AbsoluteContent(this UrlHelper urlHelper, string contentPath)
    {
        // Build a URI for the requested path
        var url = new Uri(HttpContext.Current.Request.Url, urlHelper.Content(contentPath));
        // Return the absolute UrI
        return url.AbsoluteUri;
    }
}

如果定义正确,这将使您可以简单地将 Url.Content()调用替换为 Url.AbsoluteContent(),如下所示:

If defined properly, this would allow you to simply replace your Url.Content() calls with Url.AbsoluteContent() as seen below :

Url.AbsoluteContent("~/Controller/Action")

您可以在此处查看此方法的示例.

这篇关于如何在ASP.NET MVC中将URL路径转换为完整或绝对URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆