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

查看:893
本文介绍了如何在.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应用程序配置以XML格式存储在web.config文件中.有关.Net Core应用程序的更多信息,您可以阅读 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>

之后,一切都会正常.请确保使用与.Net Framework应用程序中相同的连接字符串名称(在本例中为SHOPPINGCNN),否则将无法获得所需的结果.我在我的项目中做到了,而且效果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天全站免登陆