简体   繁体   中英

How to access a json file in an n-tier mvc application VS2015

I have a visual studio solution that contains several projects, including a service project (Business logic), and an MVC UI project(Presentation).

Within the service project I have a json file which I need to access in one of the service project classes.

The problem I have is that almost everything I try returns a path to the UI project (Not where the json file is)

Things I have tried:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "geo.json");
//returns a path contained within UI project

HttpContext.Current.Server.MapPath("~/geo.json");
// also returns a path contained within UI project

Environment.CurrentDirectory;
// returns C:\\Program Files (x86)\\IIS Express

How can I get the path to a json file that is not contained within the UI project?

Since the "service project" is a class library, you cannot really do anything relative to the path of the class library.

The class library is turned into a .dll file, at compile time, and it is copied into the bin folder of the project that references it (also at compile time).

So when the code in the service project asks where it is running from, it returns the location of the code that references it, because that's where the .dll file ends up.

I hope this makes some amount of sense. It would be much easier to explain if I could use hand puppets, but markdown does not currently support the use of funny props.

As Frank mentions in the comment above, you can tell other files in the service project to also be copied into the bin folder, by selecting the file's properties and choosing "Copy to output directory". If you do this to your geo.json file it will end up in the bin folder.

Alternatively, inside the MVC app, you could pass the path of the geo.json file into the method of the .dll as a parameter. That way it is up to the caller to know where the information is stored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM