如何快速确定我的ASP的根URL是什么?NET MVC应用程序?例如,如果IIS设置为在http://example.com/foo/bar上为我的应用程序服务,那么我希望能够以一种可靠的方式获得该URL,而不涉及从请求中获取当前URL,并以某种脆弱的方式将其分割,如果我重新路由我的操作,这种方式就会中断。
我需要基本URL的原因是这个web应用程序调用另一个需要根的调用者web应用程序的回调目的。
如何快速确定我的ASP的根URL是什么?NET MVC应用程序?例如,如果IIS设置为在http://example.com/foo/bar上为我的应用程序服务,那么我希望能够以一种可靠的方式获得该URL,而不涉及从请求中获取当前URL,并以某种脆弱的方式将其分割,如果我重新路由我的操作,这种方式就会中断。
我需要基本URL的原因是这个web应用程序调用另一个需要根的调用者web应用程序的回调目的。
当前回答
网页本身:
<input type="hidden" id="basePath" value="@string.Format("{0}://{1}{2}",
HttpContext.Current.Request.Url.Scheme,
HttpContext.Current.Request.Url.Authority,
Url.Content("~"))" />
在javascript中:
function getReportFormGeneratorPath() {
var formPath = $('#reportForm').attr('action');
var newPath = $("#basePath").val() + formPath;
return newPath;
}
这适用于我的MVC项目,希望它有帮助
其他回答
在MVC _Layout.cshtml中:
<base href="@Request.GetBaseUrl()" />
我们就是这么用的!
public static class ExtensionMethods
{
public static string GetBaseUrl(this HttpRequestBase request)
{
if (request.Url == (Uri) null)
return string.Empty;
else
return request.Url.Scheme + "://" + request.Url.Authority + VirtualPathUtility.ToAbsolute("~/");
}
}
在。net core 3.1中,我使用了这种方法:
$"{Request.Scheme}://{Request.Host}{Url.Content("~/")}"
你也可以用这个。对于剃刀页,最好使用它比其他。
https://ml-software.ch/posts/getting-the-base-url-for-an-asp-net-core-mvc-web-application-in-your-static-javascript-files
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<base href='@Url.AbsoluteContent("~/")'>
<title>@ViewBag.Title - ASP.NET Core Web Application</title>
<!-- ... -->
</head>
<body>
@{
var baseurl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + Url.Content("~");
}
@baseurl
——输出 http://localhost:49626/TEST/
这是在asp.net MVC 4中工作 在任何控制器动作中,你都可以写: 1stline获取整个url+查询字符串。 第二行删除本地路径和查询,最后一个'/'符号。 第三行在最后位置添加“/”符号。
Uri url = System.Web.HttpContext.Current.Request.Url;
string UrlLink = url.OriginalString.Replace(url.PathAndQuery,"");
UrlLink = String.Concat(UrlLink,"/" );