c# - 如何生成唯一的 12 位字母数字 key 以用于 URL

标签 c# asp.net-mvc

有没有一种方法可以生成唯一的字母数字 key (12 位数字)以在 C# 的 URL 中使用?我有一组彼此唯一的字符串,但不能直接使用它们,因为它们可能会改变,所以 URL 会中断。我有几种方法 -

a) 使用数据库表本身的主键,它对应于具有上述字符串集的行,但这似乎是一个安全问题,因为它会暴露数据库结构。

b) 使用 Guid,但它又不依赖于数据。

我们将不胜感激。

最佳答案

简短回答:否

你正在尝试的是不可能的。 您必须跟踪您已经创建的 ID。这就是数据库对递增的索引列所做的事情。 I also understand that URL shortening tools take new keys from a pool of generated unique ones .

综上所述,something like this DotNetFiddle might work其他一些答案也可能如此。

在 fiddle 中,我们对第一个示例中的主键进行哈希处理。由于只有完整哈希在计算上不可行,因为每个输入都不是唯一的,并且由于我们使用的是哈希的子字符串,因此不能保证唯一性,但可能接近。

这是 MSDN 对哈希唯一性的看法。

A cryptographic hash function has the property that it is computationally infeasible to find two distinct inputs that hash to the same value.

在第二个示例中,我们使用了时间,据我所知,递增时间保证是唯一的,所以如果您可以相信时间是准确的,这将有效。但是,如果您要依赖服务器时间等外部资源,那么也许您应该在数据库表或简单的平面文件中使用自动递增索引。

using System;
using System.Text;
using System.Security.Cryptography;

public class Program
{
    public static void Main()
    {
        UseAHash();
        UseTime();
    }

    public static void UseAHash()
    {
        var primaryKey = 123345;
        HashAlgorithm algorithm = SHA1.Create();
        var hash = algorithm.ComputeHash(Encoding.UTF8.GetBytes(primaryKey.ToString()));
        StringBuilder sb = new StringBuilder();
        for (var i = 0; i < 6; ++i)
        {
            sb.Append(hash[i].ToString("X2"));
        }

        Console.WriteLine(sb);
    }

    public static void UseTime()
    {
        StringBuilder builder = new StringBuilder();

        // use universal to avoid daylight to standard time change.
        var now = DateTime.Now.ToUniversalTime();

        builder.Append(now.DayOfYear.ToString("D3"));
        builder.Append(now.Hour.ToString("D2"));
        builder.Append(now.Minute.ToString("D2"));
        builder.Append(now.Second.ToString("D2"));
        builder.Append(now.Millisecond.ToString("D3"));

        Console.WriteLine("Length: " + builder.Length);
        Console.WriteLine("Result: " + builder);
    }
}

关于c# - 如何生成唯一的 12 位字母数字 key 以用于 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333800/

相关文章:

asp.net-mvc - MVC 4 安装失败

c# - 如何在 UWP/RT XAML 中声明系统数据类型?

asp.net-mvc - 如何使用 ASP.Net MVC5 和 OWIN 返回 StatusCode 401

c# - 如何在 ASP.NET MVC 中基于每个用户删除输出缓存?

c# - 为什么在将 Int64 转换为 Int32 时,C# 让我在没有任何错误或警告的情况下溢出,它是如何进行转换的?

c# - 如何将自定义 URL 参数添加到 MVC RedirectToAction

c# - 在 HttpPost 之后更新模型

c# - 将GPS数据转换为纬度和经度c#

c# - 如果值不为空,从多个结果中分配值的更好方法?

c# - 在 Linq to SQL 中的子表上应用 where 条件