Как получить строку подключения в классе из .NET Core 2.1 Web API без Entity Framework - PullRequest
0 голосов
/ 01 марта 2019

У меня есть служба веб-API .NET Core 2.1, и я хочу извлечь строку подключения из файла appsettings.json и использовать ее в отдельном классе базы данных, который я написал.Мне не нужно или не нужно использовать Entity Framework, к сожалению, все документы MS показывают только примеры EF.Я пробовал около 10 различных техник, но, похоже, никуда не денется.

Вот файл appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=MAXIMUS,61433;Database=Geolocation;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

И файл startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace GeoLocationService1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            //app.UseHttpsRedirection();
            app.UseMvc();
        } 
    }
}

Класс, который я использую для получения результатов хранимой процедуры:

using Microsoft.Extensions.Configuration;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Configuration;

namespace GeoLocationService1
{
    [DataObject(true)]
    public class ip2location_data
    {
        public static string GetConnStr()
        {
            // ?????
            string dbconn = ""; //need to somehow get the connection string from the appsettings.json file
            return dbconn;
        }

        public static string LastErrorMsg = string.Empty;

        [DataObjectMethod(DataObjectMethodType.Select, false)]
        public static ip2location GetGeoLocationFromIP(string IPAddress)
        {
            ip2location O = new ip2location();

            using (SqlConnection conn = new SqlConnection(GetConnStr()))
            {
                using (SqlCommand cmd = new SqlCommand("GetGeoLocationFromIP", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandTimeout = 30;
                    cmd.Parameters.AddWithValue("@IPAddress", IPAddress);

                    conn.Open();

                    try
                    {
                        using (SqlDataReader rs = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            if (rs.Read())
                            {
                                O.country_code = rs.GetString(rs.GetOrdinal(O.fld_country_code));
                                O.country_name = rs.GetString(rs.GetOrdinal(O.fld_country_name));
                                O.region_name = rs.GetString(rs.GetOrdinal(O.fld_region_name));
                                O.city_name = rs.GetString(rs.GetOrdinal(O.fld_city_name));
                                O.zip_code = rs.GetString(rs.GetOrdinal(O.fld_zip_code));
                                O.time_zone = rs.GetString(rs.GetOrdinal(O.fld_time_zone));
                            }
                        }
                        LastErrorMsg = string.Empty;                   
                    }
                    catch (Exception ex)
                    {
                        LastErrorMsg = ex.Message;
                    }
                }
            }

            return O;
        }
    }
}

Я думаю, что, возможно, было бы лучше просто сохранить строку подключения в отдельном текстовом файлеи читать это таким образом - но лучше сделать это правильно.Любая помощь приветствуется (да, я новичок в .NET Core, но не видел учебник, который не зависит от EF).

1 Ответ

0 голосов
/ 01 марта 2019

Вам необходимо импортировать:

using Microsoft.Extensions.Configuration;

Введите следующий код в вашем getConnStr:

 IConfigurationBuilder builder = new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json");

 IConfiguration Configuration = builder.Build();
 return Configuration["ConnectionStrings:DefaultConnection"];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...