You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core中如何导入Cryptographic库及解决CS0234命名空间不存在报错

报错原因
  1. 命名空间冲突:当前代码所在的命名空间下存在自定义的System类/子命名空间,编译器优先匹配你项目内的System(从报错信息System.Invoices.System可验证),而不是.NET官方根命名空间下的System
  2. 拼写错误:代码中System.Security.Crytography拼写错误,正确写法为System.Security.Cryptography(少写了字母p)
解决方法

方案1:加全局命名空间标识(快速修复)

在System前加global::强制从.NET根命名空间查找,修改后代码如下:

private void CreatePasswordCreate(string password, out byte[] passwordCreate, out byte[] passwordRepeat) {
    using (var hmac = new global::System.Security.Cryptography.HMACSHA512())
    { 
        passwordCreate = hmac.Key;
        passwordRepeat = hmac.ComputeHash(global::System.Text.Encoding.UTF8.GetBytes(password));
    }
}

方案2:顶部提前引入命名空间(推荐,代码更简洁)

在代码文件最顶部添加两行using声明:

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

方法内代码可简化为:

private void CreatePasswordCreate(string password, out byte[] passwordCreate, out byte[] passwordRepeat) {
    using (var hmac = new HMACSHA512())
    { 
        passwordCreate = hmac.Key;
        passwordRepeat = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
    }
}
相关说明
  • System.Text:.NET基础类库自带命名空间,包含编码处理、字符串操作相关类,Encoding.UTF8属于该命名空间,ASP.NET Core项目默认已引用对应程序集,无需额外安装。
  • System.Security.Cryptography:.NET基础类库自带命名空间,包含哈希、加密、签名等安全相关算法实现,HMACSHA512属于该命名空间,ASP.NET Core项目默认已引用对应程序集,无需额外安装。
  • 其他非自带类库引入方法:在IDE中右键对应项目→选择「管理NuGet程序包」→搜索对应类包名称,安装匹配你项目.NET版本的版本即可。

内容的提问来源于stack exchange,提问作者dudeiale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:54:05