1

I am using Visual Studio Code version 1.42 on my Ubuntu 18.04. I just successfully installed sudo dotnet add package Google.Apis.Drive.v3 via terminal but I can't find a way to install System.Web on my C# project.

web

I tried many different ways:

1) sudo dotnet add package Microsoft.AspNet.WebApi

2) sudo dotnet add package Microsoft.AspNet.Mvc -Version 5.2.7

3) sudo dotnet add package Microsoft.AspNet.Mvc

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
//using System.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;


namespace IHostingEnvironmentExample.Controllers
{
    public class HomeController : Controller
    {
        private IHostingEnvironment _env;
        public HomeController(IHostingEnvironment env)
        {
            _env = env;
        }
        public IActionResult Index()
        {
            var webRoot = _env.WebRootPath;
            var file = System.IO.Path.Combine(webRoot, "test.txt");
            System.IO.File.WriteAllText(file, "Hello World!");
            return View();
        }
    }
}


namespace WebApi2.Models
{
    public class GoogleDriveFilesRepository 
    {
       //defined scope.
        public static string[] Scopes = { DriveService.Scope.Drive };
        // Operations....

        //create Drive API service.
        public static DriveService GetService()
        {
             //Operations.... 

        public static List<GoogleDriveFiles> GetDriveFiles()
        {
            // Other operations....
        }

       //file Upload to the Google Drive.
        public static void FileUpload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                DriveService service = GetService();

                string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
                Path.GetFileName(file.FileName));
                file.SaveAs(path);

                var FileMetaData = new Google.Apis.Drive.v3.Data.File();
                FileMetaData.Name = Path.GetFileName(file.FileName);
                FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);

                FilesResource.CreateMediaUpload request;

                using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
                {
                    request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                    request.Fields = "id";
                    request.Upload();
                }
            }
        }


        //Download file from Google Drive by fileId.
        public static string DownloadGoogleFile(string fileId)
        {
            DriveService service = GetService();

            string FolderPath = System.Web.HttpContext.Current.Server.MapPath("/GoogleDriveFiles/");
            FilesResource.GetRequest request = service.Files.Get(fileId);

            string FileName = request.Execute().Name;
            string FilePath = System.IO.Path.Combine(FolderPath, FileName);

            MemoryStream stream1 = new MemoryStream();

            request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
            {
                switch (progress.Status)
                {
                    case DownloadStatus.Downloading:
                        {
                            Console.WriteLine(progress.BytesDownloaded);
                            break;
                        }
                    case DownloadStatus.Completed:
                        {
                            Console.WriteLine("Download complete.");
                            SaveStream(stream1, FilePath);
                            break;
                        }
                    case DownloadStatus.Failed:
                        {
                            Console.WriteLine("Download failed.");
                            break;
                        }
                }
            };
            request.Download(stream1);
            return FilePath;
        }
    }
}

Post that I consulted to find a solution to this problem were this one, this, also this one. I came across this too which seemed to be related but no luck. Also this last one was useful, however I am confused about which type of package to install.

thanks for providing guidance on how to solve this problem.

Emanuele
  • 1,860
  • 4
  • 15
  • 42
  • 2
    You are doing .NET Core development, so `System.Web` is out of scope. What do you need from there? – Lex Li Feb 25 '20 at 15:23
  • 1
    None of the packages you mentioned or linked (Microsoft.AspNet.WebApi, Microsoft.AspNet.Mvc, System.Web.Http, System.Web.Providers) are relevant to System.Web. As you mentioned Ubuntu I guess you have .NET Core project. However, System.Web is a .NET Framework assembly. Why do you need System.Web? Remove it and use the classes from .NET Core assemblies. – ckuri Feb 25 '20 at 15:24
  • 1
    If you need a web client, you should use System.Http.Net (with HttpClient) https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netcore-3.0 – Pac0 Feb 25 '20 at 15:25
  • I need to upload/download files via google drive api. the function `public static void FileUpload(HttpPostedFileBase file)` as an unresolved dependency due to (I think) that – Emanuele Feb 25 '20 at 15:27
  • Also `string path = Path.Combine(HttpContext.Current.Server.......` and also `FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);` – Emanuele Feb 25 '20 at 15:27
  • Instead of the MimeMapping class from System.Web use another package like Microsoft.AspNetCore.StaticFiles (see https://dotnetcoretutorials.com/2018/08/14/getting-a-mime-type-from-a-file-name-in-net-core/) or any MIME mapping package from NuGet, or just always set the MIME type to `application/octet-stream` if the MIME type doesn't really matter. – ckuri Feb 25 '20 at 15:28
  • @ckuri, thanks for reading the question. What do you mean? Could you please add an answer integrating your code and showing what the corrections are? – Emanuele Feb 25 '20 at 15:33
  • 1
    The static `HttpContext.Current` is only applicable for an ASP.NET MVC controller. ASP.NET Core MVC controllers have a HttpContext property - so you would need to make your methods non-static. However, is the code snippet you have shown part of a controller or is this even an ASP.NET Core project? – ckuri Feb 25 '20 at 15:34
  • I am learning how to use the google drive api and I found [this tutorial](https://everyday-be-coding.blogspot.com/p/google-drive-api-uploading-downloading.html) that explain in detail its use. I am going through it but have this last problem of the `System.Web` unresolved dependency. – Emanuele Feb 25 '20 at 15:40

1 Answers1

1

As per the code you showed, you are trying to use System.Web.HttpContext.Current.Server.MapPath, which indeed does not exist in .NET Core.

There is no more HttpContext static usable in ASP.NET Core, along with System.Web entirely.

To replace the "Server.MapPath", you can follow some guidance here : https://www.mikesdotnetting.com/Article/302/server-mappath-equivalent-in-asp-net-core

Basically, you need to access a IHostingEnvironment env object, that ASP.NET Core will happily inject.

I'd recommend not using static methods to leverage the constructor dependency injection that is performed in controller constructor automatically.

Otherwise you can also call the dependency service to get the instance (all the details of how to use the dependency service is a bit out of scope here, but feel free to comment if this is not clear)

From this, you should be able to get the path of the server :

public class HomeController : Controller 
{ 
    private IHostingEnvironment _env;
    // Injection of IHostingEnvironment dependency through constructor
    public HomeController(IHostingEnvironment env)
    {
        _env = env;
    }

    public void MyMethod() 
    {
        // here you get your replacement of "Server.MapPath" :
        var serverPath = _env.WebRootPath;


        // ...
    }
}

See also this related Q&A : How to use IHostingEnvironment

Pac0
  • 16,761
  • 4
  • 49
  • 67
  • Thanks a lot for reading the question. I went through the other posts you advised and read about it, thanks for that source :). This way I have never done it and it still looks a bit confusing for me on how to use it. I updated the question, and the code, with your suggestion but still does not work. Can I ask you the favor of updating your answer integrating my code and your code so that I can fully understand the use of it? Thank you very much for your time in reading the question again, very much appreciated :) – Emanuele Feb 26 '20 at 12:20
  • @Emanuele Yes, I'll try. Do you have an error with the example controller action `Index` that you just put into your question, or does it work and create the file alright ? If you have an exception, which is it ? – Pac0 Feb 26 '20 at 13:08
  • Thank you very much for anything you can help me with. The problem is basically that it does not compile. You can find on my [GitHub](https://github.com/emanueleraggi/WebApi2) the small example project I am trying to run on my machine. The `System.Web` is is used in 3 files: `HomeController.cs`, `GoogledrivefilesRepository.cs` and `RouteConfig.cs`. Thanks for anything you can do to help me shed light on this problem. I really appreciate that! – Emanuele Feb 26 '20 at 13:49
  • Basically : you have a HomeController that calls your repository methods. First, in the repository, remove all usages of `HttpContext.Current.Server.MapPath("~/GoogleDriveFiles")`, instead use a parameter like `baseDirectory`, that you will pass from the controller. Second, in the home controller, add the code shown to inject the IHostingEnvironment from the controller constructor. By debugging, check that the controller actually receives something as the `env` parameter (if it is null, then post another comment). – Pac0 Feb 29 '20 at 07:37
  • Third, in your controller action, use `string basePath = Path.Combine(_env.WebRootPath, "GoogleDriveFiles")`, and pass this value as the parameter mentioned in the first point. – Pac0 Feb 29 '20 at 07:37