asp.net-mvc - 如何获取文件系统路径以在 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
解决方案
避免在 API 中使用 Server.MapPath,而是使用 HostingEnvironment:
System.Web.Hosting.HostingEnvironment.MapPath("~/UploadedFiles/Foo");
推荐阅读
- kotlin - 间谍高阶函数的类型推断
- javascript - 使用 SOAPUI 到 HTML/javascript 执行 Web 服务 XML 请求
- amazon-web-services - 从 AWS SDK for Chime 检索会议和与会者列表
- python - 如何将 am*n 数组放置在 M*N 数组中?
- scala - 具有替代方法的重载方法值 createDirectStream
- java - Spring boot 和 GCP - 使用 spring-cloud-gcp-starter-sql-postgresql 连接 Cloud SQL 实例尝试 SSL 并且延迟启动
- ruby-on-rails - Antd 设计 - 堆内存不足 - webpacker
- javascript - 如何将 2d array[][] 渲染(或传递)到 html?
- python - Python Socket 正在接收意外消息
- html - 带有图像的 div 未显示在 d-flex flex-column 中