摘要:取得網頁超連結路徑置換後的新連結
最近一直在做HTML Editor的東西
有寫到一個功能是要讓使用者可輸入超連結
且需判斷輸入超連結是否有效
但使用者輸入的超連結的可能性有很多種
可能是 從根目錄來的(/test.html) 、相對路徑(../test.html) 、也有可能是連到外網去(http://tw.yahoo.com)
那要如何取得輸入超連結來置換成完整路徑呢?
.aspx檔
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="getAbsoluteUri.aspx.cs" Inherits="getAbsoluteUri" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>未命名頁面</title>
</head>
<body>
<form id="form1" runat="server">
<div>
目前網址:<asp:TextBox ID="TextBox1" runat="server" Width="500px"></asp:TextBox>
<br />
相對路徑:<asp:TextBox ID="TextBox2" runat="server" Width="500px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="轉換路徑" onclick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>未命名頁面</title>
</head>
<body>
<form id="form1" runat="server">
<div>
目前網址:<asp:TextBox ID="TextBox1" runat="server" Width="500px"></asp:TextBox>
<br />
相對路徑:<asp:TextBox ID="TextBox2" runat="server" Width="500px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="轉換路徑" onclick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
.cs檔
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class getAbsoluteUri : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Uri nowUri = new Uri(TextBox1.Text);
Uri linkUri = new Uri(nowUri, TextBox2.Text);
Label1.Text = linkUri.AbsoluteUri;
}
}執行結果
using