Running a C# FTP client against FTP server (active mode) from an Azure Function - "500 Syntax error, command unrecognized"

582 Views Asked by At

I am trying to connect to a remote FTP server that uses Active mode. I have implemented a simple C# FTP client using .NET Core 3.1

var filename = _ftpServerUrl + "/" + targetFilePath;
System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(filename);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Proxy = null;
request.Credentials = new NetworkCredential(username, password);
request.KeepAlive = false;
request.UsePassive = false;
request.UseBinary = true;       
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader(fileStream))
{
    fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(fileContents, 0, fileContents.Length);
}

This works excellent when running in VS 2019 on localhost. But when the code is running as an Azure function (v3) in Azure, I get this response from the server:

500 Syntax error, command unrecognized

I understand the FTP Active mode requires the client to send its public IP address to the server, which will then try and open and incoming connection to the client.

Is there anything in the Azure Function sandbox preventing this?

I have even tried running my Azure Function using an App Service plan with a static public IP, without any luck.

Is there anyone out there who have had success connecting to an FTP server using Active Mode from an Azure App Service or Function?

1

There are 1 best solutions below

0
Martin Prikryl On

FTP servers do not "use active mode". It's the FTP clients that may choose to use the active mode. But nowadays with ubiquitous firewalls and NATs, using the active mode can hardly work. That's true even more so in case of cloud services, VMs, and even more so with such a specific virtual services as Azure functions.

The FTP active mode needs an incoming connection. That's prevented by the Azure firewall and NATs. I'd expect that the VMs running the Azure functions won't have any incoming ports forwarded/opened. Why would they? It goes against the purpose of the Azure functions. They are intended to run a short-lived functionality, not servers. The active FTP mode is a strange beast in this respect. There's hardly any other client-side functionality that needs incoming ports.

Allowing the incoming connections (if possible at all in Azure functions) is not a programming question. No change in your code would help. In general, you should use the passive mode.

For some background, see my article about a network configuration needed for the active and passive FTP modes.