gpt4 book ai didi

c# - 如何从没有 Entity Framework 的 .NET Core 2.1 Web API 检索类中的连接字符串

转载 作者:太空狗 更新时间:2023-10-29 23:28:18 24 4
gpt4 key购买 nike

我有一个 .NET Core 2.1 Web API 服务,我希望从 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 的教程)。

最佳答案

您需要导入:

using Microsoft.Extensions.Configuration;

在您的 getConnStr 中写入以下代码:

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

IConfiguration Configuration = builder.Build();
return Configuration["ConnectionStrings:DefaultConnection"];

关于c# - 如何从没有 Entity Framework 的 .NET Core 2.1 Web API 检索类中的连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54938006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com