gpt4 book ai didi

asp.net - 如何在 ASP.NET MVC 中将 url 路径转换为完整或绝对 url?

转载 作者:行者123 更新时间:2023-12-01 08:52:50 25 4
gpt4 key购买 nike

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

假设我的网站域是 www.example.com。如果我使用 Url.Content("~/controller/action") ,它只会返回“ Controller / Action ”。我想得到"www.example.com/controller/action" .我怎么才能得到它?

最佳答案

如果您可以使用 Controller / Action 名称...

您应该使用 Url.Action() 方法。

通常,Url.Action()当仅提供 Controller 和 Action 名称时,将返回类似于您当前期望的内容:

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

但是,当您传入协议(protocol)参数(即 httphttps 等)时,该方法实际上将返回一个完整的绝对 URL。为方便起见,您可以使用 Request.Url.Scheme 访问适当协议(protocol)的属性,如下所示:
// This would yield "http://your-site.com/Controller/Action"
Url.Action("Action", "Controller", null, Request.Url.Scheme);

您可以 see an example of this in action here .

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

如果您只能访问相对 URL(即 ~/controller/action )之类的东西,那么您可能需要创建一个函数来扩展 Url.Content() 的当前功能支持提供绝对 URL 的方法:
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() 通话如下所示:
Url.AbsoluteContent("~/Controller/Action")

您可以 see an example of this approach here .

关于asp.net - 如何在 ASP.NET MVC 中将 url 路径转换为完整或绝对 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37329956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com