Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

.Net Core API read content from Json File

I am trying to read content from a json file in .Net core API and assign to a list and use it for doing business logic.

API Layers:

Project -> Business -> Repository -> DB

I need to read content from a json file in the Business layer. File content will not change frequently. I am thinking of reading the file in the Business layer class constructor.

Questions:

  1. Do I need to keep this file in App_Data folder?
  2. Can I use the HttpContextAccessor in the business layer constructor and read the content?

Can someone help in providing the best way to achieve? Please let me know if the question is not clear and I will rephrase it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do I need to keep this file in App_Data folder?

That is entirely up to your intended use of the file. If it is static data or configuration that rarely changes, you could store it with your project and set up your project to copy it to the build folder. This can be done in Visual Studio 2019 by selecting "Always Copy" or "Copy if Newer" as the Copy to Output Directory option., or in the .csproj file directly.

Can I use the HttpContextAccessor in the business layer constructor and read the content?

You can, by registering it with .Add<Transient|Scoped|Singleton>() in your Starup.ConfigureServices. Note that this make it difficult to use this business layer service in a non-request context (e.g. with a scheduled task).

However, if the file is on the same machine as the app, I don't see why you would need the HttpContext to read it. All you need is the System.IO and System.Text.Json namespaces.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...