加入收藏 | 设为首页 | 会员中心 | 我要投稿 广州站长网 (https://www.020zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > Asp教程 > 正文

ASP.Net Core 2中的全局变量

发布时间:2022-10-16 20:31:16 所属栏目:Asp教程 来源:互联网
导读: 本文介绍了ASP.Net Core 2中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在ASP.NET Core中开发一个Web应用程序,目前

本文介绍了ASP.Net Core 2中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ASP.NET Core中开发一个Web应用程序,目前有大量密钥,例如条带帐户密钥.与其将它们分散在整个项目中的不同类中,我不希望将它们全部放置在json中,以便可以在全局范围内对其进行访问.我尝试将它们放置在appsettings.json中,但无法在任何地方访问它们.

I am developing a web application in ASP.NET Core and currently have a large set of keys, such as stripe account keys. Instead of having them spread throughout the project in different classes I would like to place them all together in json where they could be accessed globally. I have tried placing them in appsettings.json but cannot access them anywhere.

推荐答案

我经常用连接字符串和其他全局常量来做这种事情.首先为所需的变量创建一个类.在我的项目中,它是MDUOptions,但是您想要的任何内容.

I often do this kind of thing with connection strings and other global constants. First create a class for those variables that you need. In my project it is MDUOptions but whatever you want.

public class MDUOptions
{
    public string mduConnectionString { get; set; }
    public string secondaryConnectionString { get; set; }
}

现在在您的Startup.cs ConfigureServices方法中:

Now in your Startup.cs ConfigureServices method:

Action mduOptions = (opt =>
{
    opt.mduConnectionString = Configuration["ConnectionStrings:mduConnection"];
});
services.Configure(mduOptions);
services.AddSingleton(resolver => resolver.GetRequiredService>().Value);

现在ASP 变量,您可以使用DI通过代码访问它:

Now you use DI to access it in code:

public class PropertySalesRepository : IPropertySalesRepository

asp.net session变量_ASP 变量_asp 变量类型

{ private static string _mduDb; public PropertySalesRepository(MDUOptions options) { _mduDb = options.mduConnectionString; } .... }

在我的情况下,我想要的唯一属性是字符串,但是我可以使用整个选项类.

In my case the only property I wanted was the string but I could have used the entire options class.

这篇关于ASP.Net Core 2中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

(编辑:广州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!