【发布时间】:2018-07-10 16:46:59
【问题描述】:
我在 VS2017 中创建了一个新的控制台应用程序,并尝试运行此代码以证明我可以在 .NET Core 中加密和解密字符串。我曾尝试从 Program.cs Main 调用 RunSample,但它希望它是一个静态方法。如果我将 RunSample 设为静态,那么在尝试设置 var protectedpayload 时会出现空引用异常。
using System;
using Microsoft.AspNetCore.DataProtection;
public class MyClass
{
private readonly IDataProtector _protector;
public MyClass(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("Contoso.MyClass.v1");
}
public void RunSample()
{
Console.WriteLine("Enter input:");
string input = Console.ReadLine();
var protectedPayLoad = _protector.Protect(input);
Console.WriteLine($"Protect returned: {protectedPayLoad}");
var unprotectedPayLoad = _protector.Unprotect(protectedPayLoad);
Console.WriteLine($"Unprotect returned: {unprotectedPayLoad}");
}
}
如何运行它?
更新:
尝试从 Program.cs 运行它,我有以下内容,但 .MyClass 有一个“无法解析”语法错误/红色下划线。
using System;
namespace encrypttest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
new Program().MyClass.RunSample();
}
}
}
更新 2:
【问题讨论】:
-
你需要一个类的实例来运行它。向我们展示你是如何从 main 方法调用它的
-
这里的依赖注入在哪里?我怀疑你根本没有创建(或注入)这个类。
-
@DavidG 我该怎么做?我需要一个 startup.cs 吗?
-
@maccettura 我已经添加了 Program.cs 代码
-
好吧,你这里根本没有依赖注入,为什么你认为你有?
标签: c# .net visual-studio asp.net-core console-application