Creating unique URLs in ASP.NET
In my website, I need to create unique URLs that an admin user would use to send it to a g开发者_Python百科roup of users. The unique URL is created whenever an admin creates a new form. I understand I can use a guid to represent unique URLs, but I am looking for something shorter (hopefully around 4 characters, since it's easier to remember). How would I generate a unique URL in ASP.NET that would look like this:
http://mydomain.com/ABCD
I understand some of the URL shortener websites (like bit.ly) does something like this with a very short unique URL. Is there an algorithm I can use?
How about something like
public static string GetRandomString (int length)
{
string charPool = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
StringBuilder sb = new StringBuilder();
Random rnd = new Random();
while ((length--) > 0)
sb.Append(charPool[(int)(rnd.NextDouble() * charPool.Length)]);
return sb.ToString();
}
and call
GetRandomString(4);
Just write an algorithm to select a certain number of characters from a GUID (e.g. the first 4 or 8 characters, every even character up to 4 or 8 characters.)
Be sure to check it against the database to make sure it isn't already in use, and if it is regenerate it. As a safeguard, maybe make a timeout (if it tries to generate 10 and they're all in use, give up,) but it's unlikely to use every possible combination.
I believe bit.ly performs a hash and then base64 encodes the result. You could do the same, although it'll be more than 4 characters. Be sure to add code that handles hashing collisions. You could append 1, 2, 3, etc. when the first hash is in use.
Another approach is to create a new table in a database. Every time you need a new URL, add a row to this table. You could use the PK as the URL value. This will give you up to 10,000 unique values using only four characters. Base64 encode for even more.
精彩评论