作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 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");
http
、
https
等)时,该方法实际上将返回一个完整的绝对 URL。为方便起见,您可以使用
Request.Url.Scheme
访问适当协议(protocol)的属性,如下所示:
// This would yield "http://your-site.com/Controller/Action"
Url.Action("Action", "Controller", null, Request.Url.Scheme);
~/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")
关于asp.net - 如何在 ASP.NET MVC 中将 url 路径转换为完整或绝对 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37329956/
我是一名优秀的程序员,十分优秀!