如何在 .Net Core 应用程序中读取 web.config 文件 [英] How to read web.config file in .Net Core app

查看:51
本文介绍了如何在 .Net Core 应用程序中读取 web.config 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个 .Net Core API 并且我向它引用了一个 .Net 框架应用程序.引用的应用程序连接到数据库,其连接字符串存储在 web.config 文件中:

I have created a .Net Core API and I referenced a .Net framework application to it. The referenced Application connects to a data base and its connection string is stored in web.config file:

    string CONNSTR =ConfigurationManager.ConnectionStrings["SHOPPINGCNN"].ConnectionString;

.Net Core 应用程序使用 appsettings.json 而不是 web.config 文件.当我运行 API 并尝试使用引用的应用程序资源时,将触发上述代码并返回 null,因为 .net Core 应用程序中不存在 web.config 文件.解决此问题的最佳解决方案是什么

The .Net Core application uses appsettings.json instead of web.config file. When I run the API and try to use the referenced application resources, the above code will be triggered and will return null because there is no web.config file exists in .net Core app. What is the best solution to resolve this issue

推荐答案

因为 .Net Core 应用程序是自托管的并且几乎可以在任何平台上运行,所以它们不再托管在 IIS 上..Net Core 应用程序设置默认存储在 Json 格式 (appsettings.json) 中,而 .Net Framework 应用程序配置存储在 web.config XML 格式的文件.有关 .Net Core 应用程序的更多信息,您可以阅读 ASP.NET Core 中的配置.就我而言,我试图从 .Net Core 2.0 程序集访问 .Net Framework 程序集的数据层.为此,无需安装 System.Configuration.ConfigurationManager 包在 .Net Core 应用程序中,但您只需要将 app.config 添加到 .Net Core 程序集中,然后向其中添加连接字符串:

Because .Net Core applications are self hosted and can almost run on any platform, they are no longer hosted on IIS. The .Net Core application settings are stored in a Json format (appsettings.json) by default while .Net Framework application configurations are stored in a web.config file in XML format. For more info about .Net Core applications, you may read Configuration in ASP.NET Core. In my case, I was trying to access the data layer of a .Net Framework assembly from a .Net Core 2.0 assembly. To achieve this, there is no need to install System.Configuration.ConfigurationManager package in the .Net Core application but you only need to add app.config to the .Net Core assembly then add the connection string to it:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="SHOPPINGCNN" connectionString="server=your server name;integrated security=true;database=your database name" />
  </connectionStrings>
</configuration>

在那之后,一切都会正常进行.确保您使用的连接字符串名称(在我的例子中为 SHOPPINGCNN)与您在 .Net Framework 应用程序中使用的相同,否则您将无法获得所需的结果.我在我的项目中做到了这一点,它 100% 有效.

After that, everything will work fine. Make sure that you use the same connection string name (SHOPPINGCNN in my case) that you used in your .Net Framework application otherwise you will not get the desired result. I did this in my project and it works 100%.

这篇关于如何在 .Net Core 应用程序中读取 web.config 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆