如何快速确定我的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应用程序的回调目的。
当前回答
@{
var baseurl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + Url.Content("~");
}
@baseurl
——输出 http://localhost:49626/TEST/
其他回答
假设你有一个Request对象可用,你可以使用:
string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
如果它不可用,你可以通过上下文获得它:
var request = HttpContext.Current.Request
这是一个asp.net属性到MVC的转换。这是一个很好的方法。
声明一个helper类:
namespace MyTestProject.Helpers
{
using System.Web;
public static class PathHelper
{
public static string FullyQualifiedApplicationPath(HttpRequestBase httpRequestBase)
{
string appPath = string.Empty;
if (httpRequestBase != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
httpRequestBase.Url.Scheme,
httpRequestBase.Url.Host,
httpRequestBase.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Url.Port,
httpRequestBase.ApplicationPath);
}
if (!appPath.EndsWith("/"))
{
appPath += "/";
}
return appPath;
}
}
}
用法:
从控制器使用:
PathHelper.FullyQualifiedApplicationPath(ControllerContext.RequestContext.HttpContext.Request)
在视图中使用:
@using MyTestProject.Helpers
PathHelper.FullyQualifiedApplicationPath(Request)
网页本身:
<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项目,希望它有帮助
在简单的html和ASP。NET或ASP。如果你正在使用标签:
<a href="~/#about">About us</a>
对于url的应用程序别名,如http://example.com/appAlias/…你可以试试这个:
var req = HttpContext.Current.Request;
string baseUrl = string.Format("{0}://{1}/{2}", req.Url.Scheme, req.Url.Authority, req.ApplicationPath);