【问题标题】:how can i check if there is some error in the http link, and then proceed?如何检查http链接中是否有错误,然后继续?
【发布时间】:2019-01-06 08:17:17
【问题描述】:

我在 mvc4 中编写了一个操作方法,它从链接下载文件,然后从该文件将数据上传到数据库中。我正在使用 Web 客户端类来下载文件。现在在这个阶段,我想知道是否有任何适当的方法来检查 url 中的错误并停止下载文件,在映射的位置保持前一个文件完好无损。这是我将文件下载到我的文件夹中的方式:

public class testController : Controller
    {

        public class MyWebClient : WebClient
        {
            protected override WebRequest GetWebRequest(Uri address)
            {
                var req = base.GetWebRequest(address);
                req.Timeout = 15000000;
                return req;
            }
        }


        public ActionResult index()
        {
            System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/App_Data/TempBrdcepPSC/PscData"));
            foreach (FileInfo csvfile in di.GetFiles())

            {
                csvfile.Delete();
            }
            MyWebClient webClient = new MyWebClient();
            webClient.DownloadFile("https://www.google.com.pk/", Server.MapPath("~/App_Data/New_folder/Summary.csv"));



            return View();
        }

    }

【问题讨论】:

  • 您要检查网址是否有效吗?或者是否存在下载文件?
  • 我想检查是否出现任何类型的错误导致下载文件出现问题,它不应该下载文件并将之前下载的文件保留在原处而不删除它。
  • 请检查解决方案可能对您有帮助:)

标签: c# asp.net validation url


【解决方案1】:

现在在这个阶段我想知道是否有任何合适的方法来 检查url中的错误

您可以使用以下方法检查您的 Uri 是否有效

public static bool URLValidatorMethod(string strURL)
{
   Uri uri;
   return Uri.TryCreate(strURL, UriKind.RelativeOrAbsolute, out uri);
}

问)TryCreate 究竟做了什么?

A) 使用指定的 System.String 实例和 System.UriKind 创建一个新的 System.Uri。并返回一个 System.Boolean 值,如果 System.Uri 已成功创建,则返回 true,否则返回 false。

您可以使用

检查网址是否有 httphttps
return Uri.TryCreate(strURL, UriKind.RelativeOrAbsolute, out uri) && uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps;

public static bool URLValidatorMethod(string strURL)
{
     return Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute); ;
}

问)IsWellFormedUriString 究竟做了什么?

A) 通过尝试用字符串构造 URI 来指示字符串是否格式正确,并确保字符串不需要进一步转义。

停止下载文件,保持前一个文件不变 映射的地方

首先通过上述方法检查您的网址是否有效,如果有效则将其保存到文件夹中,否则忽略它

这样,您之前下载的文件将不再受到影响,并且它在您映射的位置上是安全的,例如

string url = "https://www.google.com.pk/";

if (URLValidatorMethod(url))
{
    webClient.DownloadFile(url, Server.MapPath("~/App_Data/New_folder/Summary.csv"));
}
else
{
    //Do code here that you want
}

已编辑:

try
{
    string url = "https://www.google.com.pk/";

    if (URLValidatorMethod(url))
    {
        webClient.DownloadFile(url, Server.MapPath("~/App_Data/New_folder/Summary.csv"));
    }
    else
    {
        //Do code here that you want
    }
}
catch (Exception)
{
    //Do code here if you want to execute if exception occurred
}
finally
{
    //Do the code here that you want either exception occurred or not
    //Means this code run always if exception comes or not
}

如果发生特定类型的异常或错误,您可以在编写代码时修改您的 catch 块

catch (Exception ex)
{
    //You may check any particular exception and write your code
    if (ex.GetType() == typeof(ArgumentNullException))
    {
        //Do code here 
    }
    else
    if (ex.GetType() == typeof(WebException))
    {
        //Do code here 
    }
    else
    if (ex.GetType() == typeof(NotSupportedException))
    {
        //Do code here 
    }

 }

已编辑:

参考上面的详细答案,如果它对某人有帮助,这是对我有用的解决方案:

创建一个临时文件夹在那里下载您的文件,如果在下载过程中没有出现错误,它将文件从临时文件夹复制到原始位置并完成其余工作。否则,如果出现任何错误,将发送一封电子邮件指示错误,而其余代码将在实际代码流中执行而不会导致错误。

[HttpGet]
public ActionResult index(int OpCode)
{

        try
        {
            System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder"));
            foreach (FileInfo csvfile in di.GetFiles())

            {
                csvfile.Delete();
            }
            MyWebClient webClient1 = new MyWebClient();
            webClient1.DownloadFile("http://example.php", Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv"));
        }
        catch (Exception)
        {
            return RedirectToAction("ImportSendMail");

        }

        var absolutePath = HttpContext.Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/" + "Summary.csv");
        if (System.IO.File.Exists(absolutePath))
        {

            System.IO.DirectoryInfo di2 = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData"));
            foreach (FileInfo csvfile in di2.GetFiles())

            {
                csvfile.Delete();
            }

                String sourceFile = Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv");
                String destFile = Server.MapPath("~/App_Data/TempPSC/PscData/abc" + ".csv");
                        System.IO.File.Copy(sourceFile, destFile, true);


        }

        {
           //Rest of the default code that you want to run

        }

    return View();

}

【讨论】:

  • @Sadia Rashid,查看更新解决方案可能对您有帮助:)
  • 欢迎您,很高兴听到您解决了问题 :)
  • @Sadia,请在此处发布您的另一个问题,因为 stackoverflow 不允许任何人发送个人 ID 或电子邮件等
  • 发布您的问题后给我一个链接。我会注意的
  • 你对上述问题给出的答案如果链接中缺少 http 或 https,它确实有助于链接。但我真正想做的是它应该适用于任何类型的错误或链接中出现的异常,如果链接中存在任何类型的异常或错误并且它不起作用,它应该执行代码的 else 块。我已经更改了给出错误链接的代码,但它执行 if 条件而不是进入代码的“else”块。
【解决方案2】:

创建一个临时文件夹,在那里下载您的文件,如果在下载过程中没有出现错误,它会将文件从临时文件夹复制到原始位置并完成其余工作。否则,如果出现任何错误,将发送一封电子邮件指示错误,而其余代码将在实际代码流中执行而不会导致错误。

 [HttpGet]
        public ActionResult index(int OpCode)
        {

                try
                {
                    System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder"));
                    foreach (FileInfo csvfile in di.GetFiles())

                    {
                        csvfile.Delete();
                    }
                    MyWebClient webClient1 = new MyWebClient();
                    webClient1.DownloadFile("http://example.php", Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv"));
                }
                catch (Exception)
                {
                    return RedirectToAction("ImportSendMail");

                }

                var absolutePath = HttpContext.Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/" + "Summary.csv");
                if (System.IO.File.Exists(absolutePath))
                {

                    System.IO.DirectoryInfo di2 = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData"));
                    foreach (FileInfo csvfile in di2.GetFiles())

                    {
                        csvfile.Delete();
                    }

                        String sourceFile = Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv");
                        String destFile = Server.MapPath("~/App_Data/TempPSC/PscData/abc" + ".csv");
                        System.IO.File.Copy(sourceFile, destFile, true);


                }

              {
              //Rest of the default code that you want to run

              }

            return View();

        }

【讨论】:

    【解决方案3】:

    您可以通过这种方式检查HTTP错误,该功能还检查URL是否存在。

    private bool HttpValidation(string URL)
    {
        Uri urlToCheck = new Uri(URL);
        WebRequest request = WebRequest.Create(urlToCheck);
        request.Timeout = 15000;
    
        WebResponse response;
        try
        {
            response = request.GetResponse();
        }
        catch (Exception)
        {
            return false; //url does not exist or have some error
        }
    
        return true;
    }
    

    网址必须以http://https:// 形式提供。

    例如。

    if(HttpValidation("https://www.google.com.pk"))
    {
     webClient.DownloadFile("https://www.google.com.pk/",Server.MapPath("~/App_Data/New_folder/Summary.csv"));
    }
    

    如果你想检查 url 是否有效,那么你可以尝试

    Uri uriResult;
    bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); 
    

    希望对你有帮助。

    【讨论】:

    • @sadia-rashid ,你可以试试这个,对你有帮助
    【解决方案4】:

    检查错误: DownloadFile 方法抛出三个异常Ref

    • ArgumentNullException
    • WebException(这应该适合您的用例)
    • NotSupportedException

    将您的代码放入 try catch 块中。

    保持之前的文件完整: 我建议,首先下载临时文件夹中的文件,如果没有异常,然后从您刚刚下载到临时文件夹中的最新文件中替换以前的文件。

    编码愉快!!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多