RandomNumberGenerator in ASP.NET5

2019-07-13 08:54发布

问题:

I have created a new Web API project using the ASP.NET 5 Templates. I am wanting to generate random numbers using System.Security.Cryptography.RandomNumberGenerator but it is not available in the .NET Platform 5.4 (see screenshot).

Compiling it also generates the following errors:

Error   CS0234  The type or namespace name 'Cryptography' does not exist in the namespace 'System.Security' (are you missing an assembly reference?)

Error   CS0246  The type or namespace name 'RandomNumberGenerator' could not be found (are you missing a using directive or an assembly reference?)

Error   CS0103  The name 'RandomNumberGenerator' does not exist in the current context

Is there a way to use this or is there an alternative random generator that I can use which is cryptographically secure?

回答1:

I got it working thanks to Scott Chamberlain's comment by adding the System.Security.Cryptography.Algorithms NuGet package.

I also had to modify the project.json so it was only a dependency of dotnet5.4 and not a global dependency otherwise the compiler would complain that RandomNumberGenerator exists in both System.Security.Cryptography.Algorithms and mscorlib.