为什么我无法在.NET Core中找到WebRootPath?

huangapple go评论126阅读模式
英文:

why i can not find WebRootPath in .netcore

问题

以下是您的代码的中文翻译部分:

这是我的代码

当我尝试在POST方法中使用它时,它不起作用并显示错误

private readonly IWebHostEnvironment Environment;
public uploadController(IWebHostEnvironment _environment)
{
    Environment = _environment;
}

[HttpPost]
public IActionResult Upload(IFormFile file)
{
    if (file != null)
    {
        var uniqueFileName = GetUniqueFileName(file.FileName);

        var uploads = Path.Combine(Environment.WebRootPath, "Uploads");
        var filePath = Path.Combine(uploads, uniqueFileName);
        file.CopyTo(new FileStream(filePath, FileMode.Create));
    }

    return Redirect("https://google.com");
}

private string GetUniqueFileName(string fileName)
{
    fileName = Path.GetFileName(fileName);
    return Path.GetFileNameWithoutExtension(fileName)
        + "_"
        + Guid.NewGuid().ToString().Substring(0, 4)
        + Path.GetExtension(fileName);
}

请注意,我已将代码中的HTML实体代码 " 替换为双引号(")以保持代码的可读性。

英文:

this is my code

when i trying use it in method post it dont work and show me error
为什么我无法在.NET Core中找到WebRootPath?

private readonly IWebHostEnvironment Environment;
public uploadController(IWebHostEnvironment _environment)
{
Environment = _environment;

    }
    [HttpPost]
    public IActionResult Upload(IFormFile file)
    {
        if (file!= null)
        {
            var uniqueFileName = GetUniqueFileName(file.FileName);

          
            var uploads = Path.Combine(Environment.WebRootPath, "Uploads");
            var filePath = Path.Combine(uploads, uniqueFileName);
            file.CopyTo(new FileStream(filePath, FileMode.Create));
        }    


            return Redirect("https://google.com");
    }
    private string GetUniqueFileName(string fileName)
    {
        fileName = Path.GetFileName(fileName);
        return Path.GetFileNameWithoutExtension(fileName)
                  + "_"
                  + Guid.NewGuid().ToString().Substring(0, 4)
                  + Path.GetExtension(fileName);
    }

}

答案1

得分: 0

Environment.WebRootPath 如果位于项目的根目录下的 wwwroot 文件夹被意外移除,也可能为 null。

尝试将一个 wwwroot 文件夹添加到项目的根目录下。

结果:

为什么我无法在.NET Core中找到WebRootPath?

英文:

The Environment.WebRootPath can also be null if the wwwroot folder has been inadvertantly removed from the root of your project.

Try to add a wwwroot folder to the root of your project .

result:

为什么我无法在.NET Core中找到WebRootPath?

huangapple
  • 本文由 发表于 2023年2月27日 15:17:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定