0

I have a controller where I upload a file

Here is the controller

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();
        }
    }
}

When I try to build it claims that there is no Server in context. I tried HttpContext.Current.Server System.Web.HttpContext.Current.Server but I always get no X in context. What I'm missing?

Here is csproj

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

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


</Project>

Here is the current error

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

I uploaded the code to this repo https://github.com/dhilst/TodoApi2

geckos
  • 5,687
  • 1
  • 41
  • 53

1 Answers1

0

Avoid Server.MapPath in your API, use HostingEnvironment instead:

System.Web.Hosting.HostingEnvironment.MapPath("~/UploadedFiles/Foo");
  • Hi, thanks for the answer, I'm pretty new to aspnet, what is the difference? I got Server.MapPath from the documentation examples – geckos May 07 '20 at 23:57
  • 1
    I'm trying to find a link to the documentation, but what I recall is: Server.MapPath() uses internally HostingEnvironment.MapPath, however Server.MapPath requires the HttpContext before calling HostingEnvironment.MapPath() and HttpContext is available depending on how the service is hosted, in your case was not available. – UnraisedCesar May 09 '20 at 00:17
  • I tried system.web.hosting environment wihtou success too, I'm using .net core – geckos May 09 '20 at 16:40