我在哪里可以将经常更改的联系信息保留在Asp.Net Core项目中,以便可以对其进行更新(如配置文件)

斯科特·贝克

Ye Olde Asp.Net项目曾经有一个web.config文件,我可以在这里创建一个自定义配置部分和一个“配置阅读器”类,并保留一个联系人列表:

<myConfigSection>
  <contacts>
    <contact name="Luke SkyWalker" email="[email protected]" phone="123-456-7890" />
    <contact name="Anakin SkyWalker" email="[email protected]" phone="987-654-3211" />
  </contacts>  
</myConfigSection>

这使我可以从代码中轻松访问它,如果需要更新联系人,则可以更新web.config

我注意到web.configAsp.Net Core的新功能缺少该功能。实现这样的东西的首选方法是什么?

理想情况下,是数据库文件-如果愿意,可以使用简单的sqlite数据库。

否则,JSON文件将对此非常有用。如果您使用XML,则仍然可以使用XML System.Linq.Xml(与相比,API具有更好的和现代的API System.Xml)-只需将我对JsonConvertXML的反序列化库或您自己的XML读取代码替换为XML。

  1. 创建一个.json包含以下内容文件:

    {
        "contacts": [
            {
                "name": "Luke Skywalker",
                "email" : "[email protected]",
            },
            {
                "name": "Anakin SkyWalker",
                "email" : "[email protected]",
            },
            // etc
        ]
    }
    
  2. 创建对文件中的数据建模的C#POCO类型:

    class ContactsFile {
        public List<Contact> Contacts { get; set; }
    }
    class Contact {
        public String Name { get; set; }
        public String Email { get; set; }
        public String Phone { get; set; }
    }
    
  3. 在您的应用中的某处阅读:

我假设数据将被定期编辑,因此您应该在每次使用时重新加载数据-在这种情况下,应该为它创建一个新的可注入服务类。请注意,您不需要接口(但是对测试很有用)。

    public interface IContactsStore
    {
        Task<ContactsFile> ReadAsync();
    }

    public class DefaultContactsStore : IContactsStore
    {
        private readonly IHostingEnvironment env;

        public DefaultContactsStore(IHostingEnvironment env)
        {
            this.env = env;
        }

        public async Task<ContactsFile> ReadAsync()
        {
            String path = Path.Combine( this.env.ContentRootPath, "Contacts.json" );

            String fileContents;
            using( StreamReader rdr = new StreamReader( path ) )
            {
                fileContents = await rdr.ReadToEndAsync();
            }

            return JsonConvert.DeserializeObject<ContactsFile>( fileContents );
        }
    }


    public class MyController : Controller
    {
        private readonly IContactsStore contactsStore; 

        public MyController( IContactsStore contactsStore )
        {
            this.contactsStore = contactsStore;
        }

        [Route("/contacts")]
        public async Task<IActionResult> ListContacts()
        {
            ContactsFile cf = await this.contactsStore.ReadAsync();

            return this.View( model: cf );
        }
    }

    // In Startup.cs:
    public void ConfigureService( ... )
    {
        // etc
        services.AddSingleton<IContactsStore,DefaultContactsStore>();
        // etc
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章