如何从业务层程序集中获取视图的路径?

时间:2012-04-13 01:12:22

标签: asp.net-mvc asp.net-mvc-3 io

我试图将视图的内容读入字符串变量,如此 -

string _template = File.ReadAllText(@"Views/emails/registrationconfirmation.cshtml");

这样就可以与RazorEngine一起使用,从模板中创建电子邮件。

此代码位于我的业务层程序集中。我想我需要物理路径而不是我想要使用的虚拟路径。

该文件位于我的MVC3项目的Views/emails文件夹中。我如何以编程方式获取读取文件所需的正确路径?

2 个答案:

答案 0 :(得分:1)

您的业务层不应该尝试获取视图的路径。如果它需要使用这样的路径,它们应该作为参数从UI层传递。

所以在你的业务层而不是这个:

public class MyBusiness : IMyBusiness
{
    public string RenderView()
    {
        string _template = File.ReadAllText(@"Views/emails/registrationconfirmation.cshtml");
        ...
    }
}
你可以拥有这个:

public class MyBusiness
{
    public string RenderView(string viewPath)
    {
        string _template = File.ReadAllText(viewPath);
        ...
    }
}

现在,您的控制器中的调用代码负责传递正确的路径(在ASP.NET应用程序的情况下可以使用Server.MapPath函数获取,在这种情况下桌面应用程序可能是相对路径等等)。这样,您的业务层就不再与ASP.NET紧密耦合。

另一种可能性是让业务层将应用程序的基本物理路径作为构造函数参数:

public class MyBusiness : IMyBusiness
{
    private readonly string _basePath;
    public MyBusiness(string basePath)
    {
        _basePath = basePath;
    }

    public string RenderView()
    {
        var file = Path.Combine(_basePath, @"Views\emails\registrationconfirmation.cshtml");
        string _template = File.ReadAllText(viewPath);
        ...
    }
}

然后剩下的就是配置你的DI框架,以便在实例化业务层时传递HostingEnvironment.ApplicationPhysicalPath属性值。


更新:正如@jgauffin在评论部分中指出的那样,可以通过将StreamStreamReader传递给业务层来进一步改进此代码,使其甚至不依赖于文件。这将使重用和单元测试更容易完全隔离。

答案 1 :(得分:0)

Server.MapPath适用于您的情况吗?