Creating a project
mkdir TestAspNetCoreHost
cd TestAspNetCoreHost
dotnet new web --no-https
Adding the NuGet packages
# For the main FTP server
dotnet add package FubarDev.FtpServer
# For the System.IO-based file system access
dotnet add package FubarDev.FtpServer.FileSystem.DotNet
Create an IHostedService
implementation
Important
This is only required for version 3.0, because the FTP server will provide a much tighter ASP.NET Core integration in a future release.
Create a new file named HostedFtpService.cs
, which contains the following code:
using System.Threading;
using System.Threading.Tasks;
using FubarDev.FtpServer;
using Microsoft.Extensions.Hosting;
namespace TestAspNetCoreHost
{
internal class HostedFtpService : IHostedService
{
private readonly IFtpServerHost _ftpServerHost;
/// <summary>
/// Initializes a new instance of the <see cref="HostedFtpService"/> class.
/// </summary>
/// <param name="ftpServerHost">The FTP server host that gets wrapped as a hosted service.</param>
public HostedFtpService(
IFtpServerHost ftpServerHost)
{
_ftpServerHost = ftpServerHost;
}
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
return _ftpServerHost.StartAsync(cancellationToken);
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
return _ftpServerHost.StopAsync(cancellationToken);
}
}
}
Using the FTP server
Change your Program.cs
to the following code:
using System.IO;
using FubarDev.FtpServer;
using FubarDev.FtpServer.FileSystem.DotNet;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace TestAspNetCoreHost
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(
services =>
{
// Add FTP server services
// DotNetFileSystemProvider = Use the .NET file system functionality
// AnonymousMembershipProvider = allow only anonymous logins
services
.AddFtpServer(
builder => builder
.UseDotNetFileSystem()
.EnableAnonymousAuthentication());
// Configure the FTP server
services.Configure<FtpServerOptions>(opt => opt.ServerAddress = "*");
// use %TEMP%/TestFtpServer as root folder
services.Configure<DotNetFileSystemOptions>(opt => opt
.RootPath = Path.Combine(Path.GetTempPath(), "TestFtpServer"));
// Add the FTP server as hosted service
services
.AddHostedService<HostedFtpService>();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Starting the FTP server
dotnet run
Now your FTP server should be accessible at 127.0.0.1:21
.