簡體   English   中英

無法連接到遠程服務器(ftp 在開發中有效,但在生產中無效)

[英]Unable to connect to the remote server (ftp works in development but not in production)

我正在開發一個 asp.net mvc web 應用程序,該應用程序位於 web.com 托管的共享服務器上。 它在 IIS 7 和 .NET 4.0 上運行。

我收到錯誤消息“ [WebException:無法連接到遠程服務器] System.Net.FtpWebRequest.GetResponse() ”,當我的彈出表單加載它的下拉列表時,它包含我的 ftp 站點中的目錄名稱。 我能夠運行我的應用程序並連接到開發中的 ftp(使用 visual studio 2019)。 而且我能夠將 te.net 連接到 ftp(默認端口 21)。

Controller 代碼:

[NoCache]
[Authorize]
[HttpGet]
public ActionResult UploadFile()
{
    ViewData["Folders"] = GetFolders();
    return View();
}

private IEnumerable<SelectListItem> GetFolders()
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
    request.Method = WebRequestMethods.Ftp.ListDirectory;
    request.UseBinary = true;
    request.KeepAlive = false;
    request.Timeout = -1;
    request.UsePassive = true;
    request.Proxy = null;
    request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    List<SelectListItem> folders = new List<SelectListItem>();
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream);
    string names = reader.ReadToEnd();

    reader.Close();
    response.Close();

    var folderList =
        new List<string>(names.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
            .ToList());
    folders = folderList.ConvertAll(a =>
    {
        return new SelectListItem()
        {
            Text = a.ToString(),
            Value = a.ToString(),
            Selected = false
        };
    });
    return folders;
}

這是帶有原始 ftpUrl 的 ftpwebrequest 日志:

System.Net Information: 0 : [11124] Current OS installation type is 'Server'.
System.Net Information: 0 : [27548]
FtpWebRequest#25592066::.ctor(ftp://ftp.mywebsite.com/ftp/)
System.Net Information: 0 : [27548]
FtpWebRequest#25592066::GetResponse(Method=NLST.)
System.Net Error: 0 : [27548] Exception in
FtpWebRequest#25592066::GetResponse - Unable to connect to the remote server.
at System.Net.FtpWebRequest.GetResponse()

這是我將 ftpUrl 更改為 root 時的 ftpwebrequest 日志:

System.Net Information: 0 : [11124] Current OS installation type is 'Server'.
System.Net Information: 0 : [20756] 
FtpWebRequest#17494990::.ctor(ftp://ftp.mywebsite.com/)
System.Net Information: 0 : [20756] 
FtpWebRequest#17494990::GetResponse(Method=NLST.)
System.Net Error: 0 : [20756] Exception in 
FtpWebRequest#17494990::GetResponse - Unable to connect to the remote server.
at System.Net.FtpWebRequest.GetResponse()

這是我將 ftpUrl 更改為 IP 地址時的 ftpwebrequest 日志:

System.Net Information: 0 : [50288] Current OS installation type is 'Server'.
System.Net Information: 0 : [25964]
FtpWebRequest#40369685::.ctor(ftp://111.222.333.44/)
System.Net Information: 0 : [25964]
FtpWebRequest#40369685::GetResponse(Method=NLST.)
System.Net Error: 0 : [25964] Exception in
FtpWebRequest#40369685::GetResponse - Unable to connect to the remote server.
at System.Net.FtpWebRequest.GetResponse()

我是 C# 和 asp.net mvc 的新手,所以請多多包涵。 任何幫助將不勝感激!

FTP 端口可能會被過濾掉從您的服務器打開的連接。

一種選擇是在該服務器上打開一個終端(不是從您的計算機或您的開發環境)並嘗試運行 te.net 到 ftp 端點。

無論如何,如果您不能嘗試並確保您使用的是正確的 FTP 端點,您可以將當前的GetFolders代碼替換為以下將測試連接性的代碼:

using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

private IEnumerable<SelectListItem> GetFolders()
{
    try
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        request.UseBinary = true;
        request.KeepAlive = false;
        request.Timeout = -1;
        request.UsePassive = true;
        request.Proxy = null;
        request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        List<SelectListItem> folders = new List<SelectListItem>();
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream);
        string names = reader.ReadToEnd();

        reader.Close();
        response.Close();

        var folderList =
            new List<string>(names.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
                .ToList());
        folders = folderList.ConvertAll(a =>
        {
            return new SelectListItem()
            {
                Text = a.ToString(),
                Value = a.ToString(),
                Selected = false
            };
        });
        return folders;
    }
    catch (Exception ex)
    {
        var hostname = (new Uri(ftpUrl)).Host;
        bool pingable = false;
        using (Ping pinger = new Ping())
        {
            try
            {
                PingReply reply = pinger.Send(hostname);
                pingable = reply.Status == IPStatus.Success;
            }
            catch (Exception pEx)
            {
                throw new Exception($"Error pinging {hostname}: {pEx.ToString()}", pEx);
            }
        }

        if (pingable)
        {
            using (TcpClient tc = new TcpClient())
            {
                tc.Connect(hostname, 20);
                bool stat = tc.Connected;
                if (!stat)
                    throw new Exception($"Cannot connect to {hostname} on port 20", ex);

                tc.Close();
            }
            using (TcpClient tc = new TcpClient())
            {
                tc.Connect(hostname, 21);
                bool stat = tc.Connected;
                if (!stat)
                    throw new Exception($"Cannot connect to {hostname} on port 21", ex);

                tc.Close();
            }
            throw new Exception($"Could connect to {hostname} on port 20 and 21", ex);
        }
        throw new Exception($"Could not ping {hostname}", ex);
    }
}

新異常應該足以讓您意識到問題所在。

  • 如果您收到類似“Could not ping <something>”的錯誤,則主機名可以解析但無法訪問,您應該檢查 ftp 是否在不同的網絡上。
  • 如果出現“無法連接到端口 20 上的hostname ”或“無法連接到端口 21 上的ftpUrl ”之類的錯誤,則端口被過濾,您應該檢查是否有防火牆過濾它。

編輯:我剛剛意識到在ftpUrl中你包含了類似“ftp://host/path”的東西。 這就解釋了為什么你會得到“沒有這樣的主機是已知的”。 所以我只是編輯了代碼以避免這種情況。

不管怎樣,根據您的評論,FTP 正在同一台服務器上運行並檢查您之前發布的錯誤(無法連接到遠程服務器),我猜可能是 FTP 站點已停止。

如果 FTP 站點已停止,只需打開 IIS 管理器 (.netmgr),展開站點並確保 FTP 站點(它可能有任何名稱,您需要檢查綁定以確認它是 FTP)正在運行,否則啟動它。

原來你的FTP服務器其實和你的web服務器是同一台機器。 所以它是與 FTP 服務器相關的localhost主機。

通常,連接到本地主機服務器時應該沒有任何問題。 如果它不起作用,則可能是提供者明確禁止本地主機連接(盡管這很奇怪)。 你真的確定web服務器和FTP服務器是同一個嗎?


無論如何,使用 FTP 連接到本地機器是沒有意義的。如果你直接在機器上,你可以直接訪問文件——那些是本地文件。 使用System.IO類,如FileDirectory (特別是Directory.GetFiles或類似的),而不是FtpWebRequest

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM