首页 > 解决方案 > 如何获取文件系统路径以在 ASPNET MVC 中保存文件

问题描述

我有一个控制器,我可以在其中上传文件

这是控制器

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using System.Web;

namespace TodoApi.Controllers {
    [Route("[controller]")]
    public class FileUploadController : Controller
    {

        public FileUploadController()
        {
        }

        [HttpPost]
        public IActionResult Index(List<IFormFile> files)
        {
            var filePath = Server.MapPath("/UploadedFiles/Foo");
            return Ok();
        }
    }
}

当我尝试构建它时,它声称上下文中没有服务器。我试过HttpContext.Current.Server System.Web.HttpContext.Current.Server了,但在上下文中我总是没有得到 X。我错过了什么?

这是csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>


</Project>

这是当前的错误

Microsoft (R) Build Engine version 16.5.0+d4cbfca49 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 61.19 ms for /Users/gecko/code/TodoApi2/TodoApi2.csproj.
Controllers/FileUploadController.cs(24,28): error CS0103: The name 'Server' does not exist in the current context [/Users/gecko/code/TodoApi2/TodoApi2.csproj]

Build FAILED.

Controllers/FileUploadController.cs(24,28): error CS0103: The name 'Server' does not exist in the current context [/Users/gecko/code/TodoApi2/TodoApi2.csproj]
    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:02.50

我将代码上传到这个 repo https://github.com/dhilst/TodoApi2

标签: asp.net-mvc

解决方案


避免在 API 中使用 Server.MapPath,而是使用 HostingEnvironment:

System.Web.Hosting.HostingEnvironment.MapPath("~/UploadedFiles/Foo");

推荐阅读