gpt4 book ai didi

c# - C#HttpWebRequest的错误处理

转载 作者:行者123 更新时间:2023-12-03 08:49:37 24 4
gpt4 key购买 nike

我是编程新手。我需要将HttpWebRequest转换为Api的异常处理。下面是我的代码,之前我没有做过错误处理,因此,将提供一个有关如何完成此操作的示例。

    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);
}
}
}
}

最佳答案

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” 文件夹,并 检查日志。 将在此处记录异常。

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

关于c# - C#HttpWebRequest的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44714490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com