【问题标题】:Relative Path with Response.AddHeader带有 Response.AddHeader 的相对路径
【发布时间】:2010-03-05 17:09:22
【问题描述】:
在用户更改密码后,我正在运行计时器并执行重定向(AKA,通知他们密码已更改,然后将其发送回主页)。但是,我似乎无法在下面的代码中创建相对路径。下面列出了我喜欢要做的事情:
Response.AddHeader("REFRESH", "2;URL="~/pages/home.aspx");
为什么这不起作用?我如何让它工作? (我知道我可以在网站的其他部分做相对路径,但那是因为它在服务器端运行。)谢谢。
【问题讨论】:
标签:
c#
.net
response.redirect
【解决方案1】:
您需要为 REFRESH 标头指定一个绝对 URL。看看 this post 展示如何从相对 URL 获取绝对 URL(您可以使用那里显示的 ResolveServerUrl):
Response.AddHeader("REFRESH", "2;url=" + ResolveServerUrl("~/pages/home.aspx"));
供参考:
/// <summary>
/// This method returns a fully qualified absolute server Url which includes
/// the protocol, server, port in addition to the server relative Url.
///
/// Works like Control.ResolveUrl including support for ~ syntax
/// but returns an absolute URL.
/// </summary>
/// <param name="ServerUrl">Any Url, either App relative or fully qualified</param>
/// <param name="forceHttps">if true forces the url to use https</param>
/// <returns></returns>
public static string ResolveServerUrl(string serverUrl, bool forceHttps)
{
// *** Is it already an absolute Url?
if (serverUrl.IndexOf("://") > -1)
return serverUrl;
// *** Start by fixing up the Url an Application relative Url
string newUrl = ResolveUrl(serverUrl);
Uri originalUri = HttpContext.Current.Request.Url;
newUrl = (forceHttps ? "https" : originalUri.Scheme) +
"://" + originalUri.Authority + newUrl;
return newUrl;
}
/// <summary>
/// This method returns a fully qualified absolute server Url which includes
/// the protocol, server, port in addition to the server relative Url.
///
/// It work like Page.ResolveUrl, but adds these to the beginning.
/// This method is useful for generating Urls for AJAX methods
/// </summary>
/// <param name="ServerUrl">Any Url, either App relative or fully qualified</param>
/// <returns></returns>
public static string ResolveServerUrl(string serverUrl)
{
return ResolveServerUrl(serverUrl, false);
}