【问题标题】:How to maintain the right URL in C#/ASP.NET?如何在 C#/ASP.NET 中维护正确的 URL?
【发布时间】:2017-03-08 18:37:53
【问题描述】:

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

但是,当它试图调出页面时,我(通过 IE)得到“此页面无法显示”。

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

我确实在代码中进行了搜索,并找到了以下行,我认为这是原因。现在,我要问的问题:

我应该怎么做才能避免使用静态 URL 并使其成为动态的,以便它始终指向正确的域?

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

Response.Redirect(url);

谢谢。

【问题讨论】:

  • 您是否尝试过在您的网址中使用相对路径?
  • 不能从 Request 对象中获取主机吗?然后将路径附加到它?
  • @Mortan 的回答确实应该被接受。主机名只有在您跨域时才会出现,例如第 3 方 API 调用。如果您想留在当前域上,请使用相对 URL。期间。

标签: c# asp.net windows web


【解决方案1】:

在控制器中使用 HttpContext.Current.Request.Url 来查看 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";

【讨论】:

  • 喜欢新的 String.Format 语法,它很干净!
  • 谢谢。只是为了清楚起见,如下所示:string url = HttpContext.Current.Request.Url.Host; url = string.Format("http://" + currentURL + "/Specific-Folder/Specific-Page.aspx?Query={0}", Var1);
  • 我想我知道你在说什么,我会更新我的答案。
【解决方案2】:

您可以将主机段存储在您的 Web.Config 文件的 AppSettings 部分中(每个配置/环境都这样)

调试/开发 Web.Config

生产/发布 Web.Config(使用配置覆盖以将 localhost 值替换为 something.org 主机)

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

            // 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 名称等。

【讨论】:

    【解决方案3】:

    应该这样做。

    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);
    

    您应该能够省略主机名以留在当前域中。

    【讨论】:

    • 欢迎来到 SO.!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2018-09-15
    • 1970-01-01
    • 2013-01-01
    • 2011-01-06
    相关资源
    最近更新 更多