动态构建URL,但去掉端口号,或者确保HTTP而不是HTTPS



当从HTTPS页面单击导航栏中的链接时,使用BuildAbsolute创建URL的链接函数不起作用,因为URL在创建的URL中包括端口443。从我的研究来看,似乎有几种方法可以去除端口号,我正在尝试使用uri。手动托管和构建URL。

但在代码行上写着-Uri uri = new Uri(string);

我得到无效的表达式术语"字符串">

这是我在Link.cs文件中的原始函数

public static string ToCategory(string departmentId, string categoryId, string page)
{
DepartmentDetails d = CatalogAccess.GetDepartmentDetails(departmentId);
string deptUrlName = PrepareUrlText(d.Name);
CategoryDetails c = CatalogAccess.GetCategoryDetails(categoryId);
string catUrlName = PrepareUrlText(c.Name);
if (page == "1")
return BuildAbsolute(String.Format("{0}-d{1}/{2}-c{3}", deptUrlName, departmentId, catUrlName, categoryId));
else
return BuildAbsolute(String.Format("{0}-d{1}/{2}-c{3}/Page-{4}/", deptUrlName, departmentId, catUrlName, categoryId, page));
}

这是我的用户控件中调用链接函数的代码

<ul>
<asp:Datalist ID="deptList4" runat="server">
<ItemTemplate>
<asp:HyperLink ID="navCatList4" runat="server"
NavigateUrl= '<%# Link.ToCategory("4", Eval("CategoryID").ToString()) %>'
Text='<%# HttpUtility.HtmlEncode(Eval("Name").ToString()) %>'>
</asp:HyperLink><br />
</ItemTemplate>
</asp:Datalist>
</ul>

我试着用以下内容替换我的BuildAbsolute,但它不起作用

Uri uri = new Uri(string);
return (String.Format("{0}://{1}/{2}-d{3}/{4}-c{5}", uri.Scheme, uri.Host, deptUrlName, departmentId, catUrlName, categoryId));

我在这里的目标是建立url,但要确保如果链接是从https页面点击的,则不会使用443端口或https来建立链接,因为这会导致页面无法加载。

感谢提供的任何帮助

感谢

替换保存了一天的函数,并根据解决我问题的建议将我上面的代码调整为下面的代码。

return BuildAbsolute(String.Format("{0}-d{1}/{2}-c{3}", deptUrlName, departmentId, 
catUrlName, categoryId)).Replace(":443", "").Replace("https://", "http://");

如果你有一个URL字符串可能包含一些不需要的部分,那么你可以这样做:

var sanitizedUrl = urlString.Replace(":443","").Replace("https://","http://");

您正在调用函数BuildAbsolute(字符串)来呈现绝对URL。这个函数很可能是从被请求的页面中获取URL端口和协议,并使用这些信息来构建您的URL。

在https或路径中有端口的页面上,它将被添加到返回的新路径中。

您需要更改。您需要使用一个新函数,从请求的基本URL中删除协议和端口,然后创建您的URL。

最新更新