【问题标题】:The name 'Server' does not exist in the current context当前上下文中不存在名称“服务器”
【发布时间】:2020-03-28 16:32:35
【问题描述】:

我有一个剃刀视图页面,我需要在尝试向用户显示文件之前检查文件是否存在,否则显示默认图像占位符。 下面是我写的代码

@{
 if (!string.IsNullOrEmpty(@parent.Photo) && File.Exists(Server.MapPath($"~/images/parents/thumbs/@parent.Photo")))
    {
      <img src="~/images/parents/thumbs/@parent.Photo" class="rounded- 
       circle img-fluid" />
     }
     else
     {
      @: No photo
     }
 }

但我收到如下错误提示

名称“服务器”在当前上下文中不存在

所以我无法构建应用程序。 我试图在视图页面上添加以下 using 语句

using System;
using System.IO;

但没区别

我的应用程序在 Windows 10 上的 ASP.NET-Core 3.1 上运行

【问题讨论】:

    标签: c# razor asp.net-core-mvc asp.net-core-3.1 file-management


    【解决方案1】:

    Server.MapPath 不会在 ASP.NET.Core 中退出,您应该使用 IWebHostEnvironment 接口。将IWebHostEnvironment 注入您的视图并使用它。

    @inject IWebHostEnvironment env
    
    @{
     var path = Path.Combine(env.WebRootPath, $"images/parents/thumbs/@parent.Photo"));
     if (!string.IsNullOrEmpty(@parent.Photo) && File.Exists(path))
        {
          <img src="~/images/parents/thumbs/@parent.Photo" class="rounded- 
           circle img-fluid" />
         }
         else
         {
          @: No photo
         }
     }
    

    更多信息请阅读这篇文章 Server.MapPath Equivalent in ASP.NET Core.

    【讨论】:

    • @inject IWebHostEnvironment env 给出以下错误消息“找不到类型或命名空间 IWebHostEnvironment(您是否缺少 using 指令或程序集引用?)
    • 如果你使用 ASP.NET Core 3.x 完整命名空间是 Microsoft.AspNetCore.Hosting.IWebHostEnvironment ,如果你使用 ASP.NET Core 2.x 命名空间是 Microsoft.Extensions.Hosting.IHostEnvironment
    • 'string' 不包含'Combine' 的定义,并且找不到接受'string' 类型的第一个参数的可访问扩展方法(您是否缺少 using 指令或程序集引用?) .也就是做上述推荐后的新错误信息
    • var path = System.IO.Path.Combine(env...
    猜你喜欢
    • 2016-08-13
    • 2013-10-02
    • 2014-04-22
    • 2017-06-17
    • 2015-09-11
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    相关资源
    最近更新 更多