将自定义命名空间导入 ASPX

Import custom namespace into ASPX

提问人:yeho 提问时间:4/2/2020 最后编辑:yeho 更新时间:3/9/2021 访问量:869

问:

我有一个位于命名空间内的类,它本身位于 .cs 文件(C#)中。

我想将该命名空间导入到我的 ASPX 网页文件中并在那里使用它。我该怎么做?

我要导入的类:

namespace PasswordEncryption
{
    public static class StringCipher

我想将此命名空间导入到我的 ASPX 页面。 这两个文件(类 C# 文件和 ASPX 文件)位于同一文件夹中。

编辑:添加了代码。

<%@ Page Language="C#"%>
<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.Data.OleDb" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.Collections.Generic" %>
<%@ Import namespace="System.IO" %>
<%@ Import namespace="System.Linq" %>
<%@ Import namespace="System.Security.Cryptography" %>
<%@ Import namespace="System.Text" %>

<%
        string connectionStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + AppDomain.CurrentDomain.BaseDirectory + @"\Login\database.mdb;User Id=admin;Password=;";
        OleDbConnection connection = new OleDbConnection(connectionStr);
        if (!(Request.Form.AllKeys.Contains("username") && Request.Form.AllKeys.Contains("firstName") && Request.Form.AllKeys.Contains("lastName")
            && Request.Form.AllKeys.Contains("email") && Request.Form.AllKeys.Contains("password"))) {
            Response.Write("Form has been tampered with.");
        } else {
            string firstName = Request.Form["firstName"];
            string lastName = Request.Form["lastName"];
            string username = Request.Form["username"];
            string email = Request.Form["email"];
            string password = Request.Form["password"];
            Regex nameRegex = new Regex(@"^[A-Za-z]+$");
            Regex usernameRegex = new Regex(@"^[A-Za-z0-9_.]+$");
            Regex emailRegex = new Regex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$");
            Regex passwordRegex = new Regex(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&*()_+\-\\/\[\].])[A-Za-z\d!@#$%^&*()_+\-\\/\[\].]{8,36}$");
            if (firstName.Length == 0 || firstName.Length > 14 || lastName.Length == 0 || lastName.Length > 14
                || username.Length == 0 || username.Length > 16 || email.Length == 0 || email.Length > 45 ||
                password.Length == 0 || password.Length > 36) {
                Response.Write("Form has been tampered with.");
            } else if (!(nameRegex.IsMatch(firstName) || nameRegex.IsMatch(lastName) || usernameRegex.IsMatch(username) || emailRegex.IsMatch(email) || passwordRegex.IsMatch(password))) {
                Response.Write("Form has been tampered with.");
            } else {
                string queryUsername = "SELECT COUNT(*) FROM Users WHERE Username = \"" + username + "\";";
                string queryEmail = "SELECT COUNT(*) FROM Users WHERE Email = \"" + email + "\";";
                password = StringCipher.Encrypt(password, password);
                string querySuccess = "INSERT INTO Users VALUES(\"" + username + "\", \"" + password + "\", \"" + email + "\", \"" + firstName + "\", \"" + lastName + "\");";
                OleDbCommand commandUsername = new OleDbCommand(queryUsername, connection);
                OleDbCommand commandEmail = new OleDbCommand(queryEmail, connection);
                OleDbCommand commandCreateUser = new OleDbCommand(querySuccess, connection);
                connection.Open();
                int userExist = (int)commandUsername.ExecuteScalar();
                int emailExist = (int)commandEmail.ExecuteScalar();
                if (userExist > 0) {
                    Response.Write("This username is taken.");
                } else if (emailExist > 0) {
                    Response.Write("This address is already in use.");
                } else {
                    commandCreateUser.ExecuteNonQuery();
                    Response.Write("Success!");
                }
            }
        }}
%>

<% // THE CODE BELOW IS THE CODE I WANT TO ADD USING AN EXTERNAL METHOD (EXTERNAL FILE)
    public static class StringCipher
    {
        // This constant is used to determine the keysize of the encryption algorithm in bits.
        // We divide this by 8 within the code below to get the equivalent number of bytes.
        private const int Keysize = 128;

        // This constant determines the number of iterations for the password bytes generation function.
        private const int DerivationIterations = 1000;

        public static string Encrypt(string plainText, string passPhrase)
        {
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
            // so that the same Salt and IV values can be used when decrypting.  
            var saltStringBytes = Generate128BitsOfRandomEntropy();
            var ivStringBytes = Generate128BitsOfRandomEntropy();
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 128;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Convert.ToBase64String(cipherTextBytes);
                            }
                        }
                    }
                }
            }
        }

        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [16 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 16 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 16 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 128;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                            }
                        }
                    }
                }
            }
        }

        private static byte[] Generate128BitsOfRandomEntropy()
        {
            var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.
            using (var rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with cryptographically secure random bytes.
                rngCsp.GetBytes(randomBytes);
            }
            return randomBytes;
        }
    
%>

编辑:我的解决方案是将我的命名空间和类编译为动态链接库文件 (.dll) 并将其导入构建文件夹中。从那里,我可以使用这条线。<%@ Import namespace="PasswordEncryption" %>

C# asp.net 命名空间

评论

0赞 Hany Habib 4/2/2020
请在 aspx 中包含您的代码以及您希望实现的目标,以便我们提供帮助
0赞 yeho 4/2/2020
我想将我的类包含在 ASPX 页中。我会相应地更新问题。
0赞 Hany Habib 4/2/2020
尝试 <%=PasswordEncryption.StringCipher....%>如果这是你的意思,我会把它作为答案发布
0赞 yeho 4/2/2020
真的不起作用..我只想在我的 ASPX 页面中使用我的 C# 类。
0赞 Hany Habib 4/2/2020
你能说说你的意思吗?以及 aspx 页面的示例。.因为我提到的这个标签是在 aspx 中注入代码,所以我认为我弄错了您的要求

答:

0赞 Selim Yildiz 4/2/2020 #1

假设你有这样的 c# 方法:(警告:类必须是,函数必须是Test()publicpublic static)

namespace PasswordEncryption
{
    public static class StringCipher
    {
        public static string Test()
        {
            return "Example string";
        }
    }
}

并且还需要将此命名空间添加到 aspx 文件中:

<%@ Import Namespace="PasswordEncryption" %>

然后,您可以在 aspx 中调用此函数,如下所示:

<%= StringCipher.Test() %>

评论

0赞 yeho 4/2/2020
找不到类型或命名空间名称“PasswordEncryption”(是否缺少 using 指令或程序集引用?
0赞 Selim Yildiz 4/2/2020
我已经测试了这段代码,应该没有问题,因为它们都在同一个项目中。你不能从你的代码后面访问namepsace吗?PasswordEncryption
0赞 yeho 4/2/2020
我真的不知道,这就是我寻求帮助的原因。我尝试导入它,我尝试搜索如何导入它,它只是不起作用。同样,正如我所说,我正在尝试将 .cs 文件导入 .aspx,两者都在同一文件夹和项目中。这就是错误消息。
0赞 Selim Yildiz 4/2/2020
你能把你的aspx文件添加到问题中吗?
1赞 yeho 8/19/2020 #2

最终使用 DLL 执行此操作。 我在 C# 中制作了函数,编译为 DLL,然后导入了它。