简体   繁体   English

在业务层中使用Server.MapPath

[英]Use Server.MapPath in Business Layer

My business layer creates files and needs to save them in the App_Data folder of my asp.net mvc 4 web frontend. 我的业务层创建文件,需要将它们保存在我的asp.net mvc 4 web前端的App_Data文件夹中。

I could use Server.MapPath in the business layer to get the physical path of the App_Data folder. 我可以在业务层中使用Server.MapPath来获取App_Data文件夹的物理路径。 But i want to avoid a reference to System.Web in the business layer. 但我想避免在业务层中引用System.Web

Are there other ways to get the path to App_Data in business layer? 是否有其他方法可以在业务层中获取App_Data的路径?

The correct way to deal with this is to have the presentation layer pass the path into the business layer. 处理此问题的正确方法是使表示层将路径传递到业务层。

To put this another way, the purpose of having a business layer is to create a separation of concerns between the ui and business processes. 换句话说,拥有业务层的目的是在ui和业务流程之间创建关注点分离。 If you force the business process to know about the ui layer, then you are violating that separation of concerns. 如果您强制业务流程了解ui层,那么您就违反了关注点。

There are a number of ways you could deal with this. 有很多方法可以解决这个问题。 You could pass the path into the business layer when the business layer is constructed, such as via constructor initialization or through dependency injection. 在构造业务层时,您可以将路径传递到业务层,例如通过构造函数初始化或通过依赖注入。 Or you could pass it to the method call. 或者您可以将其传递给方法调用。 Or you could create some form of configuration file that your business layer loads that contains the path. 或者,您可以创建某种形式的配置文件,业务层加载包含路径的配置文件。

There are lots of ways of going about this that do not violate separation of concerns. 有很多方法可以解决这个问题。

您可以使用

string  path = System.AppDomain.CurrentDomain.BaseDirectory+"App_Data";
string path = HostingEnvironment.MapPath("~\\App_Data");

这个对我有用

I know its an old question but still a very valid one. 我知道它是一个古老的问题但仍然是一个非常有效的问题。 I have seen all answers here and I want to write notes of the best of all knowledge here. 我在这里看到了所有答案,我想在这里写下最好的知识笔记。

  1. It is recommended NOT to use System.Web assembly as it conflicts SOLID principles. 建议不要使用System.Web程序集,因为它与SOLID原则冲突。 For Example, If we use System.Web and try to use that DLL in a Windows Form / Console / WPF application then context will always remain null in that scenario. 例如,如果我们使用System.Web并尝试在Windows窗体/控制台/ WPF应用程序中使用该DLL,那么在该场景中上下文将始终保持为空。
  2. For example you can want to access data.txt file under the folder App_data folder. 例如,您可以要访问data.txt文件夹下的文件App_data文件夹。 In DLL you should use following Code 在DLL中,您应该使用以下代码

    string rootDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; string pathFinalAccessFile = Path.Combine(rootDirectoryPath, "App_Data", "data.txt");

Rather than appending path and file name manually with quotes and "\\" you should use Path.Combine Method in C# (as shown in code above) . 而不是手动用引号和“\\”附加路径和文件名,你应该在C#中使用Path.Combine方法(如上面的代码所示)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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