在MVC 6中读取文件

本文关键字:读取 文件 MVC | 更新日期: 2023-09-27 17:53:36

我想访问服务器主文件夹中的create.sql文件。它包含用于设置我的数据库的查询。我访问这个文件有问题。

1( 我真的无法通过Configuration到达那里。我只能使用AddJsonFileAddXmlFileAddIniFile。我想这不是把一个大的sql文件放入其中的最佳主意。

2( github上的Mvc源似乎缺少MapPath。因此不可能使用Server.MapPath("~/create.sql")

那么如何实现呢?

在MVC 6中读取文件

正如已经注意到并在评论中提到的,ASP中似乎没有MapPath。NET VNext(MVC 6(。我在这里找到了解决方法:

http://forums.asp.net/t/2005166.aspx?HostingEnvironment+等效+For+MapPath

基本上,您需要从IApplicationEnvironment接口获得ApplicationBasePath,该接口目前作为服务实现,如下所示:

    private readonly IApplicationEnvironment _appEnvironment;
    public HomeController(IApplicationEnvironment appEnvironment)
    {
        _appEnvironment = appEnvironment;
    }
    public IActionResult Index()
    {
        var rootPath = _appEnvironment.ApplicationBasePath;
        return View();
    }

此外,您可以使用PlatformServices.Default.Application.ApplicationBasePath而不是注入IApplicationEnvironment

EDIT:以下是MapPath/UnmapPath作为PlatformServices:扩展的可能实现

removed (see EDIT2)

EDIT2:略有修改,添加了IsPathMapped()以及一些检查,以查看是否真的需要路径映射/取消映射。

public static class PlatformServicesExtensions
{
    public static string MapPath(this PlatformServices services, string path)
    {
        var result = path ?? string.Empty;
        if (services.IsPathMapped(path) == false)
        {
            var wwwroot = services.WwwRoot();
            if (result.StartsWith("~", StringComparison.Ordinal))
            { 
                result = result.Substring(1); 
            }
            if (result.StartsWith("/", StringComparison.Ordinal))
            { 
                result = result.Substring(1);
            }
            result = Path.Combine(wwwroot, result.Replace('/', ''''));
        }
        return result;
    }
    public static string UnmapPath(this PlatformServices services, string path)
    {
        var result = path ?? string.Empty;
        if (services.IsPathMapped(path))
        {
            var wwwroot = services.WwwRoot();
            result = result.Remove(0, wwwroot.Length);
            result = result.Replace('''', '/');
            var prefix = (result.StartsWith("/", StringComparison.Ordinal) ? "~" : "~/");
            result = prefix + result;
        }
        return result;
    }
    public static bool IsPathMapped(this PlatformServices services, string path)
    {
        var result = path ?? string.Empty;
        return result.StartsWith(services.Application.ApplicationBasePath,
            StringComparison.Ordinal);
    }
    public static string WwwRoot(this PlatformServices services)
    {
        // todo: take it from project.json!!!
        var result = Path.Combine(services.Application.ApplicationBasePath, "wwwroot");
        return result;
    }
}

EDIT3:PlatformServices.WwwRoot()返回实际执行路径,在.net core 2.0的DEBUG模式下,它是xxx''bin''DEBUG''netcoreapp2.0,这显然不是必需的。相反,将PlatformServices替换为IHostingEnvironment,并使用environment.WebRootPath