【问题标题】:c# Error handling for HttpWebRequestc# HttpWebRequest 的错误处理
【发布时间】:2017-06-23 06:29:24
【问题描述】:

我对编程很陌生。我需要对我的HttpWebRequestApi 进行异常处理。下面是我的代码,我之前没有做过错误处理,所以只是一个如何完成这个的例子将不胜感激。

    private void button1_Click(object sender, EventArgs e)
    {
        Class1.PostDevices x = new Class1.PostDevices();

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
        request.ContentType = "application/json";
        request.Method = "POST";
        request.Timeout = 5000;

        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            string jsonstring;
            MemoryStream stream1 = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));

            x.notification = new Class1.Notification();
            x.profile = "dev";
            x.notification.message = "Hello World";

            ser.WriteObject(stream1, x);
            stream1.Position = 0;
            StreamReader sr = new StreamReader(stream1);

            jsonstring = sr.ReadToEnd();
            Debug.WriteLine(JObject.Parse(jsonstring));

            streamWriter.Write(jsonstring);
            streamWriter.Flush();
        }
        HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
        if (httpResponse.StatusCode == HttpStatusCode.OK)
        {
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string result = streamReader.ReadToEnd();
                Debug.WriteLine(JObject.Parse(result));
                Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
            }
        }
    }
}

【问题讨论】:

  • 在 'try{ } catch(Exception objex)' 块中定义你的代码并记录它。对于日志记录,您可以创建自定义异常记录器以存储在文件中,也可以使用任何 3rd 方库,例如 Log4Net...等。
  • 您当前的应用程序是asp.net web 应用程序吗?
  • 是的。你能告诉我怎么做吗

标签: c# error-handling exception-handling httpwebrequest


【解决方案1】:

1) 在您的应用程序中创建一个名为 "ExceptionTextFile" 的文件夹

2) 像下面这样创建一个单独的类来记录异常

using System;
using System.IO;
using context = System.Web.HttpContext;

//Define your application namespace here
namespace YourApplicationNamespace
{
    public static class ExceptionLogging
    {
        private static String ErrorlineNo, Errormsg, extype, exurl,  ErrorLocation;

        public static void SendErrorToText(Exception ex)
        {
            var line = Environment.NewLine + Environment.NewLine;

            ErrorlineNo = ex.StackTrace.ToString();
            Errormsg = ex.Message;
            extype = ex.GetType().ToString();
            exurl = context.Current.Request.Url.ToString();
            ErrorLocation = ex.Message.ToString();
            try
            {
                //Create a folder named as "ExceptionTextFile" inside your application
                //Text File Path
                string filepath = context.Current.Server.MapPath("~/ExceptionTextFile/");  
                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }
                //Text File Name
                filepath = filepath + DateTime.Today.ToString("dd-MM-yy") + ".txt";   
                if (!File.Exists(filepath))
                {
                    File.Create(filepath).Dispose();
                }
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    string error = "Log Written Date:" + " " + DateTime.Now.ToString() 
                    + line + "Error Line No :" + " " + ErrorlineNo + line 
                    + "Error Message:" + " " + Errormsg + line + "Exception Type:" + " " 
                    + extype + line + "Error Location :" + " " + ErrorLocation + line 
                    + " Error Page Url:" + " " + exurl + line + line;
                    sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");
                    sw.WriteLine("-------------------------------------------------------------------------------------");
                    sw.WriteLine(line);
                    sw.WriteLine(error);
                    sw.WriteLine("--------------------------------*End*------------------------------------------");
                    sw.WriteLine(line);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (Exception e)
            {
                e.ToString();
            }
        }
    }
}

然后在您的按钮单击事件中定义 try...catch 块并记录如下异常

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        Class1.PostDevices x = new Class1.PostDevices();

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
        request.ContentType = "application/json";
        request.Method = "POST";
        request.Timeout = 5000;

        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            string jsonstring;
            MemoryStream stream1 = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));

            x.notification = new Class1.Notification();
            x.profile = "dev";
            x.notification.message = "Hello World";

            ser.WriteObject(stream1, x);
            stream1.Position = 0;
            StreamReader sr = new StreamReader(stream1);

            jsonstring = sr.ReadToEnd();
            Debug.WriteLine(JObject.Parse(jsonstring));

            streamWriter.Write(jsonstring);
            streamWriter.Flush();
        }
        HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
        if (httpResponse.StatusCode == HttpStatusCode.OK)
        {
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string result = streamReader.ReadToEnd();
                Debug.WriteLine(JObject.Parse(result));
                Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
            }
        }
    }
  } 
  catch (Exception e)
  {
     ExceptionLogging.SendErrorToText(e);                
  }
}

如果出现任何错误,请转到 "ExceptionTextFile" 文件夹并检查日志。将在此处记录异常。

如果这能解决您的问题,请尝试回复我

【讨论】:

  • 不客气 :)
猜你喜欢
  • 1970-01-01
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多