简体   繁体   English

ASP.Net Core中的自定义类

[英]Custom classes in ASP.Net Core

New to .NET Core I'm trying to make a custom class, that I can call from different controllers. .NET Core的新功能,我试图创建一个自定义类,可以从其他控制器调用它。

In the root of my project I've created a folder called Helpers. 在项目的根目录下,我创建了一个名为Helpers的文件夹。 In that I've created EncryptString.cs: 在那我创建了EncryptString.cs:

namespace VPV.Helpers {
    public class EncryptString {
        public string Index(string val, string salt) {
            byte[] data = Encoding.UTF8.GetBytes(val + salt);
            data = SHA512.Create().ComputeHash(data);
            return Convert.ToBase64String(data);
        }
    }
}

But how do I call that from my controller? 但是,如何从控制器中调用它呢?

I've tried something like: 我已经尝试过类似的东西:

public async Task<IActionResult> OnPostAsync(Guid id, string password, string passwordCheck) {
    hashedPassword = new VPV.Helpers.EncryptString [...]
}

But I'm stuck from there. 但是我被困在那里。

I think you probably wanted that to be a static call. 我想您可能希望这是一个静态电话。 However the better approach would be to make that helper an injectable service, but not sure if you may consider that too advanced or overkill. 但是,更好的方法是使该帮助程序成为可注射的服务,但是不确定您是否可能认为它太高级或太高了。

I only suggested it as you indicated that it would be used by multiple controllers. 我只是建议它,正如您指出的那样,它将被多个控制器使用。

Now since you mentioned that you wanted to keep it simple and, while not the best of designs, make the method static, 现在,既然您提到要保持简单,虽然不是最好的设计,但要使方法静态,

namespace VPV.Helpers {    
    public static class Strings {    
        public string Encrypt(string val, string salt) {
            byte[] data = Encoding.UTF8.GetBytes(val + salt);
            data = SHA512.Create().ComputeHash(data);
            return Convert.ToBase64String(data);
        }
    }
}

and call it where needed. 并在需要时调用它。

public async Task<IActionResult> OnPostAsync(Guid id, string password, string passwordCheck) {
    //...

    var hashedPassword = new VPV.Helpers.Strings.Encrypt(password, salt);

    //...
}

You could also consider converting the helper to an extension method 您也可以考虑将帮助程序转换为扩展方法

namespace VPV.Helpers {    
    public static class Strings {    
        public string Encrypt(this string val, string salt) {
            byte[] data = Encoding.UTF8.GetBytes(val + salt);
            data = SHA512.Create().ComputeHash(data);
            return Convert.ToBase64String(data);
        }
    }
}

which would then mean that you can call it like 这意味着您可以像这样称呼它

public async Task<IActionResult> OnPostAsync(Guid id, string password, string passwordCheck) {
    //...

    var hashedPassword = password.Encrypt(salt);

    //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM