Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MSBUILD:错误MSB1003:指定项目或解决方案文件_C#_Asp.net Core - Fatal编程技术网

C# MSBUILD:错误MSB1003:指定项目或解决方案文件

C# MSBUILD:错误MSB1003:指定项目或解决方案文件,c#,asp.net-core,C#,Asp.net Core,我试图在键入时构建的示例应用程序的说明 dotnet restore 在命令行 dotnet --version 报告 2.1.300 当我这样做时,我得到以下错误 MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file. 我正在执行命令的文件夹包含.cs文件,但不包含.s

我试图在键入时构建的示例应用程序的说明

dotnet restore 
在命令行

dotnet --version 
报告

2.1.300
当我这样做时,我得到以下错误

MSBUILD : error MSB1003: Specify a project or solution file.
The current working directory does not contain a project or solution file.
我正在执行命令的文件夹包含.cs文件,但不包含.sln或.csproj文件

.NetCore是否需要.csproj文件

代码来自对的回答,但github项目已被删除

我确实尝试创建了一个.csproj文件,但我很难猜到要放入哪些包

[更新]

我添加了以下.csproj文件

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

</Project>
我知道如何使用package manager,但我如何找到所有内容的正确版本

这里是program.cs

using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace dotnetconsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(@"This Application must be run after running the powershell script Setup.ps1!
                                This DotNet Console Application authenticates to Key Vault!
                                It also creates a Secret Key Value Pair!
                                And then it gets the Secret Key Value Pair!");

            bool isWindows = System.Runtime.InteropServices.RuntimeInformation
                                               .IsOSPlatform(OSPlatform.Windows);
            string KEYVAULT_URI = String.Empty;
            string APPLICATION_ID = String.Empty;
            string CERT_THUMBPRINT = String.Empty;
            if(isWindows)
            {
                KEYVAULT_URI = System.Environment.GetEnvironmentVariable("VAULT_NAME", EnvironmentVariableTarget.User);
                APPLICATION_ID = System.Environment.GetEnvironmentVariable("APPLICATION_ID", EnvironmentVariableTarget.User);
                CERT_THUMBPRINT = System.Environment.GetEnvironmentVariable("CERT_THUMBPRINT", EnvironmentVariableTarget.User);    
            }
            else 
            {
                var result = GetVariablesFromJSON();
                APPLICATION_ID = result.Item1;
                CERT_THUMBPRINT = result.Item2;
                KEYVAULT_URI = result.Item3;
            }            
            KeyVault keyVaultObj = new KeyVault(APPLICATION_ID, CERT_THUMBPRINT);
            var VaultName = "https://" + KEYVAULT_URI + ".vault.azure.net/";            
            var waitHandle = keyVaultObj.CreateSecretKeyValuePair(VaultName);    
            Console.WriteLine("Vault URI is! {0}", VaultName);
            Console.WriteLine("Wait method is invoked to wait for Secret Key Value pair to be created");
            waitHandle.Wait();
            Console.WriteLine("Secret Key Value pair is now created");            
            keyVaultObj.GetResult(VaultName);
        }

        private static Tuple<string, string, string> GetVariablesFromJSON()
        {
            var ServicePrincipalJSON = Directory.GetCurrentDirectory() + "/ServicePrincipal.json";
            var CertThumbprintJSON = Directory.GetCurrentDirectory() + "/CertThumbprint.txt";
            var VaultJSON = Directory.GetCurrentDirectory() + "/KeyVault.json";
            if(File.Exists(ServicePrincipalJSON) && File.Exists(CertThumbprintJSON) && File.Exists(VaultJSON))
            {
                return new Tuple<string, string, string>(ProcessFile(ServicePrincipalJSON, "appId", true), ProcessFile(CertThumbprintJSON, "", false), ProcessFile(VaultJSON, "name", true));
            } 

            return new Tuple<string, string, string>("", "", "");
        }

        private static string ProcessFile(string fileName, string valueToLookFor, bool isJson)
        {
            var result = "";
            using (StreamReader ContentsOfFile = File.OpenText(fileName))
            {
                if(isJson){
                    var stuff = (JObject)JsonConvert.DeserializeObject(ContentsOfFile.ReadToEnd());
                    result = stuff[valueToLookFor].Value<string>();
                }
                else {
                    var contents = ContentsOfFile.ReadToEnd();
                    contents = contents.Split("=")[1];
                    result = Regex.Replace(contents, @"\t|\n|\r", "");
                }
            }            
            return result;
        }
    }
}
这是KeyVault.cs

using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.KeyVault;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Azure.KeyVault.Models;
using System.Runtime.InteropServices;
using System.Security.Cryptography;

namespace dotnetconsole
{
    public class KeyVault
    {
        KeyVaultClient _keyVaultClient;
        string APPLICATION_ID, CERT_THUMBPRINT;
        public KeyVault(string APPLICATION_ID, string CERT_THUMBPRINT) {
            this.APPLICATION_ID = APPLICATION_ID;
            this.CERT_THUMBPRINT = CERT_THUMBPRINT;
            _keyVaultClient = new KeyVaultClient(this.GetAccessToken);
        }

        public static ClientAssertionCertificate AssertionCert { get; set; }

        // This method is used to get a token from Azure Active Directory. 
        public async Task<string> GetAccessToken(string authority, string resource, string scope)
        {
            var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation
                                               .IsOSPlatform(OSPlatform.Windows);

            X509Certificate2 certByThumbprint = new X509Certificate2();
            if(isWindows){
                certByThumbprint = FindCertificateByThumbprint(this.CERT_THUMBPRINT);
            } else {
                // If it's a pem file then we take the private key portion and create a 
                // RSACryptoServiceProvider and then we create a x509Certificate2 class from the cert portion 
                // and then we combine them both to become one x509Certificate2
                RSACryptoServiceProvider rsaCryptoServiceProvider = Util.PemFileReader();
                certByThumbprint = Util.ConvertFromPfxToPem("cert.pem");
                certByThumbprint = certByThumbprint.CopyWithPrivateKey(rsaCryptoServiceProvider);
            }

            AssertionCert = new ClientAssertionCertificate(this.APPLICATION_ID, certByThumbprint);
            var result = await context.AcquireTokenAsync(resource, AssertionCert);
            return result.AccessToken;
        }


        public async Task CreateSecretKeyValuePair(string vaultBaseURL)
        {
            System.Console.WriteLine("Authenticating to Key Vault using ADAL Callback to create Secret Key Value Pair");
            System.Console.WriteLine(vaultBaseURL);
            KeyVaultClient kvClient = new KeyVaultClient(this.GetAccessToken);
            await kvClient.SetSecretAsync(vaultBaseURL, "TestKey", "TestSecret");
        }

        // In this method we first get a token from Azure Active Directory by using the self signed cert we created in our powershell commands
        // And then we pass that token to Azure Key Vault to authenticate the service principal to get access to the secrets
        // Finally we retrieve the secret value that was created previously 
        public void GetResult(string keyvaultUri)
        {
            try
            {
                var result = this._keyVaultClient.GetSecretAsync(keyvaultUri, "TestKey").Result.Value;
                System.Console.WriteLine("Secret Key retrieved is {0} and value is {1}, ", "TestKey", result);    
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        // In Windows this method would find the certificate that's stored in the certificate manager under current user
        // Given a thumbprint this method finds the certificate       
        public static X509Certificate2 FindCertificateByThumbprint(string findValue)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint,
                    findValue, false); // Don't validate certs, since the test root isn't installed.
                if (col == null || col.Count == 0 )
                    return null;
                return col[0];
            }
            finally
            {
                store.Close();
            }
        }
    }
}
[更新]

工具->Nuget软件包管理器->管理解决方案的软件包报告错误

Microsoft Visual Studio
The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
[更新]

我保存了所有内容,关闭了.sln文件并重新打开。然后我进入了Nuget软件包管理器

[更新]

我已经安装了Microsoft.Azure.KeyVault(3.0.0)和Newtonsoft.Json(11.0.2) 我在Microsoft.IdentityModel.Clients.ActiveDirectory中遇到问题 当我尝试Microsoft.IdentityModel时,它是错误的框架

Package 'Microsoft.IdentityModel 6.1.7600.16394' was restored using ''.NETFramework, Version=v4.61'
instead of the projecttargetframework '.NETCoreApp,Version=v2.1' 
This package may not be fully compatible with your project
[更新] 谷歌搜索“使用Microsoft.IdentityModel.Clients.ActiveDirectory核心”

发现 并在下午跑步

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 3.19.8
[更新] 尝试使用语句搜索Bouncy Castle并找到

Install-Package BouncyCastle.NetCore -Version 1.8.2
[更新]

重建全部成功,现在我在的第47行有一个运行时错误

var waitHandle=keyVaultObj.CreateSecretKeyValuePair(VaultName)


发生错误是因为我没有.csproj文件,作者没有将其包含在源代码中。
该问题记录了我构建过程中的步骤。

当前工作目录是否包含项目或解决方案文件?从哪个目录运行此命令?谢谢,我更新了该问题。我收到的代码中没有.csproj或.sln文件,因此需要先修复它…您是如何创建此项目的?请与我们分享有关您的项目结构的屏幕截图。您应该将问题和答案分开,并将答案部分放在此处:)
Package 'Microsoft.IdentityModel 6.1.7600.16394' was restored using ''.NETFramework, Version=v4.61'
instead of the projecttargetframework '.NETCoreApp,Version=v2.1' 
This package may not be fully compatible with your project
Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 3.19.8
Install-Package BouncyCastle.NetCore -Version 1.8.2
  System.AggregateException
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at dotnetconsole.Program.Main(String[] args) in C:\dev2018\key-vault-dotnet-quickstart\Program.cs:line 47

Inner Exception 1:
ArgumentNullException: Value cannot be null.