ASP.NET 核心中的 FileStream 构造函数

FileStream Constructors in ASP.NET Core

在ASP.NET中,我们可以通过FileStream.FileStream(string path, FileMode mode, FileAccess access);如下实现:

public class LoginController : MMBaseController
{  
    [AllowAnonymous]
    public ActionResult Home(string returnUrl){ 
        var fileStream = new FileStream(Server.MapPath("~/key.crt"), FileMode.Open, FileAccess.Read);
        string text;
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            text = streamReader.ReadToEnd();
        }
        Response response = new Response(text, samlTmp);
    }
}

public class MMBaseController : Controller
{
    //Controller for SignIn, SignOut, OnException, Dispose etc..
}

我尝试了以下代码:

[AllowAnonymous]
public ActionResult Home(string returnUrl, [FromService] IWebHostEnvironment environment)
{
    var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);
    string text;
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
    {
        text = streamReader.ReadToEnd();
    }
}

但是显示:

The type or namespace name 'FromService' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'FromServiceAttribute' could not be found (are you missing a using directive or an assembly reference?)

我们可以在 .NET Core 中实现同样的功能吗?我需要传递文件路径并指定文件模式以及文件 read/write 权限。

我试过了File.Open()。但是即使在添加命名空间 using System.IO;

之后我也会收到此错误

The name 'Server' does not exist in the current context

改用System.IO.File.Open(path, FileMode, FileAccess)

https://docs.microsoft.com/fr-fr/dotnet/api/system.io.file.open?view=net-6.0#system-io-file-open(system-string-system-io-filemode-system-io-fileaccess)

var fileStream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read);

所以两件事

  1. File 是您 Controller 上的一种方法。您需要使用全名 System.IO.File
  2. 在 .NET Core 中,您应该注入 IWebHostEnvironment,然后调用 environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath 来解析密钥文件的相对路径。

总而言之,您的示例可能看起来像这样

public IActionResult YourMethod([FromServices]IWebHostEnvironment environment)
{
    var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);
    string text;
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
    {
        text = streamReader.ReadToEnd();
    }
    Response response = new Response(text, samlTmp);
......

你应该也能减少

var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);

var fileStream = environment.ContentRootFileProvider.GetFileInfo("/key.crt").CreateReadStream();