如何在C#/ ASP.NET中维护正确的URL?

时间:2017-03-08 18:37:53

标签: c# asp.net windows web

我获得了一个代码,并在其中一个页面上显示了一个"搜索结果"在显示不同的项目之后,它允许用户点击其中一个记录,并且预期会打开一个页面,以便可以修改特定的选定记录。

然而,当它试图调出页面时(我通过IE浏览器)"此页面无法显示"。

很明显网址是错误的,因为首先我看到http://www.Something.org/Search.aspx然后变成http://localhost:61123/ProductPage.aspx

我在代码中搜索并找到以下行,我认为这是原因。现在,问题我不得不问:

我应该怎么做才能避免使用静态网址并使其动态化,以便始终指向正确的域名?

string url = string.Format("http://localhost:61123/ProductPage.aspx?BC={0}&From={1}", barCode, "Search");

Response.Redirect(url);

感谢。

3 个答案:

答案 0 :(得分:2)

在控制器中使用HttpContext.Current.Request.Url查看网址。 Url包含许多内容,包括Host,这是您正在寻找的内容。

顺便说一句,如果您使用最新的.Net 4.6+,您可以像这样创建字符串:

string url = $"{HttpContext.Current.Request.Url.Host}/ProductPage.aspx?BC={barCode}&From={"Search"}";

或者您可以使用string.Format

string host = HttpContext.Current.Request.Url.Host;
string url = string.Format("{0}/ProductPage.aspx?BC={1}&From={2}"), host, barCode, "Search";

答案 1 :(得分:1)

这应该这样做。

string url = string.Format("ProductPage.aspx?BC={0}&From={1}", barCode, "Search");
Response.Redirect(url);

如果您使用的是.Net 4.6+,您也可以使用此字符串插值版本

string url = $"ProductPage.aspx?BC={barcode}&From=Search";
Response.Redirect(url);

您应该只能省略主机名以保留当前域名。

答案 2 :(得分:1)

您可以将主机段存储在Web.Config文件的 AppSettings 部分中(按照配置/环境,如此)

调试/开发Web.Config

    

enter image description here

生产/发布Web.Config(使用config覆盖将somethinghost值替换为something.org主机)

    

enter image description here

然后在你的代码中使用它。

            // Creates a URI using the HostUrlSegment set in the current web.config
        Uri hostUri = new Uri(ConfigurationManager.AppSettings.Get("HostUrlSegment"));

            // does something like Path.Combine(..) to construct a proper Url with the hostName 
            // and the other url segments. The $ is a new C# construct to do string interpolation
            // (makes for readable code)
        Uri fullUri = new Uri(hostUri, $"ProductPage.aspx?BC={barCode}&From=Search");

            // fullUrl.AbosoluteUri will contain the proper Url 
        Response.Redirect(fullUri.AbsoluteUri);

Uri类有很多有用的属性和方法可以为您提供Relative UrlAbsoluteUrl,您的网址FragmentsHost等等。

enter image description here