.net core2.1 MVC 读取文件夹文件并返回

protected string basePath
{
    get
    {
        var basePath = AppDomain.CurrentDomain.BaseDirectory;
        return basePath;
    }
}
public IActionResult File(string path)
{
	var localPath = basePath;
    if (!string.IsNullOrEmpty(path)) localPath = path.Replace("~/", basePath);
	bool isDirExists = System.IO.Directory.Exists(localPath);
    bool isFileExists = System.IO.File.Exists(localPath);
    
    if (isFileExists)
    {
        var provider = new FileExtensionContentTypeProvider();
        FileInfo fileInfo = new FileInfo(localPath);
        var ext = fileInfo.Extension;
        string contentType = string.Empty;
        provider.Mappings.TryGetValue(ext, out contentType);
        return File(System.IO.File.ReadAllBytes(localPath), contentType ?? "application/octet-stream", fileInfo.Name);
    }
    else
	{
	    return File(System.Text.Encoding.UTF8.GetBytes("{\"message\":\"这不是一个文件路径!\"}"), "application/json");
	}
}

你可能感兴趣的:(.net,core,学习,实用)