代码之家  ›  专栏  ›  技术社区  ›  geckos

如何获取文件系统路径以在ASPNET MVC中保存文件

  •  0
  • geckos  · 技术社区  · 4 年前

    我有一个上传文件的控制器

    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。我错过了什么?

    <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
    

    我把代码上传到这个回购 https://github.com/dhilst/TodoApi2

    0 回复  |  直到 4 年前
        1
  •  0
  •   UnraisedCesar    4 年前

    避免服务器.MapPath在API中,请改用HostingEnvironment:

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