【问题标题】:Referencing appsettings.json from Main method throws ConnectionString not Initialized从 Main 方法引用 appsettings.json 会引发 ConnectionString not Initialized
【发布时间】:2019-06-12 05:00:50
【问题描述】:

我正在构建一个需要与 SQL Server 交互的 .NET Core 2.2 控制台应用程序。我创建了一个 appsettings.json 文件来存储我的连接字符串。 我的程序的Main方法如下:

class Program
{
    private static IConfiguration _iconfiguration;
    static void Main(string[] args)
    {
            try
            {
                GetAppSettingsFile();
                ProPayService.MerchantSignUpForProPay();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            Console.WriteLine("\r\nPress any key to continue");
            Console.Read();
    }

    static void GetAppSettingsFile()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        _iconfiguration = builder.Build();
        Console.WriteLine(_iconfiguration);
    }
}

我的 appsettings.json 位于项目的主目录中,并且我已将 Copy 设置为 Output Directory = Copy Always。

我通过以下方式设置我的数据访问类:

public class OnboardingDAL
{
    private readonly string _connectionString;

    public OnboardingDAL(IConfiguration iconfiguration)
    {
        _connectionString = iconfiguration.GetConnectionString("Development");

    }

    public SqlConnection GetConnection()
    {
        SqlConnection connection = new SqlConnection(_connectionString);
        SqlCommand cmd = new SqlCommand("GetUnsentOnboardingRecords_sp", connection);
        if (connection.State == ConnectionState.Closed)
        {
            connection.Open();
        }

        return connection;
    }
    public List<Onboarding> GetOnboardingList(IConfiguration iconfiguration)
    {
        string connectionString = _connectionString;
        connectionString = iconfiguration.GetConnectionString("Development");
        var listOnboardingModel = new List<Onboarding>();
        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("GetUnsentOnboardingRecords_sp", connection);

                cmd.CommandType = CommandType.StoredProcedure;
                connection.Open();

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        listOnboardingModel.Add(new Onboarding
                        {

                            UserId = (int)reader[1],
                            UserName = reader[2].ToString(),
                            FirstName = reader[3].ToString(),
                            MiddleInitial = reader[4].ToString(),
                            Lastname = reader[5].ToString(),
                            DateOfBirth = (DateTime?)reader[6],
                            Ssn = reader[7].ToString(),
                            Email = reader[8].ToString(),
                            Address1Line1 = reader[9].ToString(),
                            Address1Line2 = reader[10].ToString(),
                            Address1ApartmentNumber = reader[11].ToString(),
                            Address1City = reader[12].ToString(),
                            Address1State = reader[13].ToString(),
                            Address1ZipCode = reader[14].ToString(),
                            Address1Country = reader[15].ToString(),
                            DayPhone = reader[16].ToString(),
                            EveningPhone = reader[17].ToString(),
                            PhonePin = reader[18].ToString(),
                            MerchantSourceIp = reader[19].ToString(),
                            ThreatMetrixPolicy = reader[20].ToString(),
                            SessionId = reader[21].ToString(),
                            BankAccount1Name = reader[22].ToString(),
                            BankAccount1CountryCode = reader[23].ToString(),
                            BankAccount1Number = reader[24].ToString(),
                            BankAccount1BankName = reader[25].ToString(),
                            BankAccount1OwnershipType = reader[26].ToString(),
                            BankAccount1RoutingNumber = reader[27].ToString(),
                            BankAccount2CountryCode = reader[28].ToString(),
                            BankAccount2Name = reader[29].ToString(),
                            BankAccount2Number = reader[30].ToString(),
                            BankAccount2BankName = reader[31].ToString(),
                            BankAccount2OwnershipType = reader[32].ToString(),
                            BankAccount2RoutingNumber = reader[33].ToString(),
                            AuthSginerFirstName = reader[34].ToString(),
                            AuthSignerLastName = reader[35].ToString(),
                            AuthSignerTitle = reader[36].ToString(),
                            AverageTicket = (decimal?)(reader[37]),
                            BusinessLegalName = reader[37].ToString(),
                            BusinessAddressLine1 = reader[38].ToString(),
                            BusinessAddressLine2 = reader[39].ToString(),
                            BusinessCity = reader[40].ToString(),
                            BusinessState = reader[41].ToString(),
                            BusinessZipCode = reader[42].ToString(),
                            BusinessCountry = reader[43].ToString(),
                            BusinessDescription = reader[44].ToString(),
                            DoingBusinessAs = reader[45].ToString(),
                            Ein = reader[46].ToString(),
                            HighestTicket = (decimal?)(reader[47]),
                            MerchantCategoryCode = reader[47].ToString(),
                            MonthlyBankCardVolume = (decimal?)(reader[48]),
                            OwnerFirstName = reader[48].ToString(),
                            OwnerLastName = reader[49].ToString(),
                            OwnerSsn = reader[50].ToString(),
                            OwnerDob = (DateTime?)reader[51],
                            OwnerAddress = reader[52].ToString(),
                            OwnerCity = reader[53].ToString(),
                            OwnerRegion = reader[54].ToString(),
                            OwnerZipCode = reader[55].ToString(),
                            OwnerCountry = reader[56].ToString(),
                            OwnerTitle = reader[57].ToString(),
                            OwnerPercentage = (decimal?)reader[58],
                            BusinessUrl = reader[59].ToString(),
                            CreditCardNumber = reader[60].ToString(),
                            ExpirationDate = reader[61].ToString(),
                            PaymentMethodId = reader[62].ToString(),
                            PaymentBankAccountNumber = reader[63].ToString(),
                            PaymentBankRoutingNumber = reader[64].ToString(),
                            PaymentBankAccountType = reader[65].ToString(),
                            Transmitted = reader[66].ToString(),
                            TransmitDate = (DateTime?)reader[67]
                        });
                    }
                }
                connection.Close();
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        return listOnboardingModel;
    }
}

然后我使用以下类来获取我的数据库字段值并调用 ProPay API,如下所示:

 public class ProPayService
 {
    private static HttpClient _httpClient = new HttpClient();
    private readonly string _baseUrl = "https://xmltestapi.propay.com/ProPayAPI";

    /// <summary>
    /// Executes a particular http request to a resource.
    /// </summary>
    /// <typeparam name="T">The response type.</typeparam>
    /// <param name="request">The REST request.</param>
    /// <param name="url"></param>
    /// <param name="baseUrl">The base URL.</param>
    /// <returns>Returns a response of the type parameter.</returns>
    private static T Execute<T>(IRestRequest request, string baseUrl) where T : class, new()
    {

        var client = new RestClient(baseUrl);
        var response = client.Execute<T>(request);

        if (response.ErrorException != null)
        {
            Console.WriteLine(
                "Error: Exception: {0}, Message: {1}, Headers: {2}, Content: {3}, Status Code: {4}",
                response.ErrorException,
                response.ErrorMessage,
                response.Headers,
                response.Content,
                response.StatusCode);
        }

        return response.Data;
    }

     public static ProPayResponse MerchantSignUpForProPay()
     {
        var baseUrl = "https://xmltestapi.propay.com/ProPayAPI";
        var request = BuildMerchantTestData();
        var restRequest = CreateRestRequest("SignUp", Method.PUT);
        restRequest.AddJsonBody(request);
        return Execute<ProPayResponse>(restRequest, baseUrl);
    }

    /// <summary>
    /// Builds the merchant request data.
    /// </summary>
    /// <returns>The request data.</returns>

    private static IConfiguration iconfiguration;

    private static readonly SOBOContext _context;
    private string _connectionString;

    public ProPayService(IConfiguration iconfiguration)
    {
       //_connectionString = iconfiguration.GetConnectionString("Development");
       var myProPayService = new ProPayService(iconfiguration);
       var connectionString = new SqlConnection(this._connectionString);
    }
    //private static ProPayResponse _proPayResponse;
    private static async Task<SignUpRequest> BuildMerchantTestData()
    {

            var onboardingDAL = new OnboardingDAL(iconfiguration);
            var onboardingList = onboardingDAL.GetOnboardingList(iconfiguration);

            onboardingList.ForEach(result =>
            {
                Console.WriteLine("{0} {1}", result.Email, result.User.UserId);
                var signupRequest = new SignUpRequest
                {
                    SignupAccountData = new SignupAccountData
                    {
                        ExternalId = "12345",
                        Tier = "",
                        CurrencyCode = "USD",
                        PhonePIN = result.PhonePin,
                        UserId = result.UserId
                    },
                    PersonalData = new PersonalData
                    {
                        DateOfBirth = Convert.ToDateTime(result.DateOfBirth),
                        SourceEmail = result.Email,
                        SocialSecurityNumber = result.Ssn,
                        FirstName = result.FirstName,
                        LastName = result.Lastname,
                        MiddleInitial = result.MiddleInitial,
                        PhoneInformation =
                            new PhoneInformation
                                {DayPhone = result.DayPhone, EveningPhone = result.EveningPhone}
                    },
                    Address = new Address
                    {
                        Address1 = result.Address1Line1,
                        Address2 = result.Address1Line1,
                        ApartmentNumber = result.Address1ApartmentNumber,
                        City = result.Address1City,
                        State = result.Address1State,
                        Country = result.Address1Country,
                        Zip = result.Address1ZipCode
                    },
                    BusinessAddress =
                        new Address
                        {
                            Address1 = result.BusinessAddressLine1,
                            Address2 = result.BusinessAddressLine2,
                            ApartmentNumber = "",
                            City = result.BusinessCity,
                            State = result.BusinessState,
                            Country = result.BusinessCountry,
                            Zip = result.BusinessZipCode
                        },
                    MailAddress = new Address
                    {
                        Address1 = result.OwnerAddress,
                        City = result.OwnerCity,
                        State = result.OwnerRegion,
                        Country = result.OwnerCountry,
                        Zip = result.OwnerZipCode
                    },
                    BankAccount =
                        new BankAccount
                        {
                            AccountCountryCode = result.BankAccount1CountryCode,
                            AccountType = result.BankAccount1Type,
                            AccountOwnershipType = result.BankAccount1OwnershipType,
                            BankAccountNumber = result.BankAccount1Number,
                            BankName = result.BankAccount1BankName,
                            RoutingNumber = result.BankAccount1RoutingNumber
                        },
                    SecondaryBankAccount =
                        new BankAccount
                        {
                            AccountCountryCode = result.BankAccount2CountryCode,
                            AccountType = result.BankAccount2Type,
                            AccountOwnershipType = result.BankAccount2OwnershipType,
                            BankAccountNumber = result.BankAccount2Number,
                            BankName = result.BankAccount2BankName,
                            RoutingNumber = result.BankAccount2RoutingNumber
                        },
                    BusinessData =
                        new BusinessData
                        {
                            BusinessLegalName = result.BusinessLegalName,
                            DoingBusinessAs = result.DoingBusinessAs,
                            EIN = result.Ein,
                        },
                    CreditCardData = new CreditCardData
                    {
                        CreditCardNumber = result.CreditCardNumber, // test card number
                        ExpirationDate = Convert.ToDateTime(result.ExpirationDate)
                    }
                };
                Console.WriteLine(JsonConvert.SerializeObject(signupRequest));
            });

            return new SignUpRequest();
    }

    /// <summary>
    /// Request factory to ensure API key is always first parameter added.
    /// </summary>
    /// <param name="resource">The resource name.</param>
    /// <param name="method">The HTTP method.</param>
    /// <returns>Returns a new <see cref="RestRequest"/>.</returns>
    private static RestRequest CreateRestRequest(string resource, Method method)
    {

        var credentials = GetCredentials();

        var restRequest = new RestRequest { Resource = resource, Method = method, RequestFormat = DataFormat.Json, };
        restRequest.AddHeader("accept", "application/json");
        restRequest.AddHeader("Authorization", credentials);
        restRequest.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
        return restRequest;
    }

    private static string GetCredentials()
    {
        var termId = "myterm"; // put affiliate term id here, if you have it
        var certString = "mycert"; // put affiliate cert string here
        var encodedCredentials = Convert.ToBase64String(Encoding.Default.GetBytes(certString + ":" + termId));

        var credentials = $"Basic {encodedCredentials}";
        return credentials;
    }
}

程序抛出以下错误:The ConnectionString property has not been initialized.

为了正确初始化 ConnectionString,我需要修改什么?

【问题讨论】:

  • 你在哪里设置 _connectionString 变量?它在哪里声明?
  • 我更新了我的问题以反映我如何设置变量。这是正确的方法吗?
  • 我看到这个构造函数 public ProPayService(IConfiguration iconfiguration) { _connectionString = iconfiguration.GetConnectionString("Development");但是我没有看到构造函数被调用....你在哪里使用这个构造函数创建一个新实例?
  • 好的,现在你已经改变了构造函数.....你需要把它放回原来的样子。第二个 BuildMerchantTestData 不应该是静态的。第三个私有静态IConfiguration iconfiguration;在 ProPayService 中也不应该是静态的。您的主要方法中的第四个是您需要实例化 var myProPayService = new ProPayService(iconfiguration); 的地方。在您致电 MerchantSignupForProPay 之前,它也不应该是静态的
  • @Darkonekt 请发布答案,以便我奖励它。谢谢!!

标签: c# sql-server


【解决方案1】:

您需要对代码进行一些更改:

首先,您的构造函数需要如下所示:

public ProPayService(IConfiguration iconfiguration)
{
   _connectionString = iconfiguration.GetConnectionString("Development");     
}

第二个BuildMerchantTestData 和MerchantSignUpForProPay 不应该是静态的。

第三个字段IConfiguration iconfiguration 在 ProPayService 类中不应是静态的

在你的 main 方法中,你应该实例化你的 PeyProService 类并像这样调用你的方法:

static void Main(string[] args)
{
        try
        {
            GetAppSettingsFile();

            var service = new ProPayService(_iconfiguration);

            service.MerchantSignUpForProPay();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }


        Console.WriteLine("\r\nPress any key to continue");
        Console.Read();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多