从Main方法引用appsettings.json会抛出未初始化的ConnectionString

时间:2019-06-10 17:55:17

标签: c# sql-server

我正在构建一个需要与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驻留在项目的主目录中,并且将“复制到输出目录”设置为“始终复制”。

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

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?

1 个答案:

答案 0 :(得分:1)

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

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

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

第二个BuildMerchantTestDataMerchantSignUpForProPay不应是静态的。

在ProPayService类中,第三字段IConfiguration iconfiguration不应为静态

在主要方法中的第四,您应该实例化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();
}