gpt4 book ai didi

asp.net-core - 从(虚拟)波浪号引用路径获取完整 URL

转载 作者:行者123 更新时间:2023-12-04 03:16:24 24 4
gpt4 key购买 nike

通过波浪号使用相对路径命名法时,如何获取完整的 URL 字符串?例如,如果我想使用相对路径在我的 View 中引用某些内容...

~/images/mylogo.jpg

我想获得完整的 url,这样它最终看起来像......

https://myserver:8081/images/mylogo.jpg

这是填充 Open Graph 的元标记所必需的.我正在尝试使用 ...

<meta property="og:image" content="@Url.Content("~/images/mylogo.jpg")" />

...但这只给出了导致...的相对路径

<meta content="/images/mylogo.jpg" property="og:image">

详细信息 - 需要检测是否使用了 SSL。需要确定当前端口和主机名...

最佳答案

可能重复的答案在 Getting absolute URLs using ASP.NET Core MVC 6非常相似,但没有解决代字号的使用问题。对于代字号,我使用了 URL Helper 'Content' 方法。为了完整起见,这里是我着陆的地方......

创建扩展方法...

using Microsoft.AspNetCore.Mvc;

namespace testProject.Utilities
{
public static class MVCExtensionMethods
{
public static string BaseUrl(this IUrlHelper helper)
{
var url = string.Format("{0}://{1}", helper.ActionContext.HttpContext.Request.Scheme, helper.ActionContext.HttpContext.Request.Host.ToUriComponent());
return url;
}

public static string FullURL(this IUrlHelper helper, string virtualPath)
{
var url = string.Format("{0}://{1}{2}", helper.ActionContext.HttpContext.Request.Scheme, helper.ActionContext.HttpContext.Request.Host.ToUriComponent(), helper.Content(virtualPath));

return url;
}
}
}

通过 Razor 在 View 中使用...

@using testProject.Utilities

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<meta property="og:url" content="@Url.BaseUrl()" />
<meta property="og:type" content="website" />
<meta property="og:title" content="@ApplicationConstants.ApplicationTitle" />
<meta property="og:description" content="@ApplicationConstants.TagLine" />
<meta property="og:image" content="@Url.FullURL("~/images/logo-black.png")" />

<title>@ApplicationConstants.ApplicationTitle</title>

<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />

@Html.ApplicationInsightsJavaScript(TelemetryConfiguration)
</head>
<body>
</body>
</html>

总结...

MVC 有两种助手 - HTML 助手和 URL 助手。我在使用 HTML 助手时试图获取 URL。应该改用 URL 帮助器。可能的重复答案指示我改为查看 URL 帮助器。它没有显示波浪线虚拟目录命名法的使用......

关于asp.net-core - 从(虚拟)波浪号引用路径获取完整 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40620752/

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